Forum: Ruby on Rails Modifying data before update or save

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B0e227ae419295321ca2aff4c27ad99d?d=identicon&s=25 Nic Werner (Guest)
on 2005-12-20 05:50
(Received via mailing list)
Hi,

I'd like to upcase a variable before it is saved, but I'm not sure how
to access the incoming param or where this work should be performed:

In my update method, I have:

@device = Device.find(params[:id])
    params[:device[macaddress]].upcase  <-- problem code
    if @device.update_attributes(params[:device])
....usual stuff here

'macaddress' is the variable I'd like to upcase.

Does anybody have suggestions?

- Nic.
648805ae18e92b7c71e46f3caa23ddc8?d=identicon&s=25 Ed C. (Guest)
on 2005-12-20 05:56
(Received via mailing list)
Nic,

In your model, I think you want to hook into the before_save callback,
like:

before_save :normalize

def normalize
  macaddress.upcase!
  #other modifications here
end

Hope that helps,
Regards,
Ed C.
Cee0292fffa691f1fb320d5400200e99?d=identicon&s=25 Marcel Molina Jr. (Guest)
on 2005-12-20 06:05
(Received via mailing list)
On Mon, Dec 19, 2005 at 08:48:20PM -0800, Nic Werner wrote:
> 'macaddress' is the variable I'd like to upcase.
>
> Does anybody have suggestions?

You could use a before_save callback in the Device model.

class Device < ActiveRecord::Base
  before_save :normalize_macaddress

  # ...

  private
    def normalize_macaddress
      self.macaddress = macaddress.upcase if macaddress
    end
end

marcel
This topic is locked and can not be replied to.