Modifying data before update or save


#1

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.

#2

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.


#3

On Mon, Dec 19, 2005 at 08:48:20PM -0800, Nic W. 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