Carl Edwards Carl Edwards - 1 year ago 88
Ruby Question

Capitalizing more than one attribute in a Rails before_save method

I'd like to capitalize the

of my model instances using the
method. Of course I could do this:

before_save do
self.first_name = first_name.capitalize
self.last_name = last_name.capitalize

But I'd much rather alter the two attributes in one fell swoop. Is there a way to select certain columns in my model and apply the desired method to them?

Answer Source

You could do something like this

before_save :capitalize_attributes

   def capitalize_attributes
     capitalizable = ["first_name","last_name"]
     self.attributes.each do |attr,val|
       #based on comment either of these will work
       #if you want to store nil in the DB then
       self.send("#{attr}=",val.strip.capitalize) if capitalizable.include?(attr) && !val.nil?
       #if you want to store a blank string in the DB then 
        self.send("#{attr}=",val.to_s.strip.capitalize) if capitalizable.include?(attr)

Then you can just add the attributes you want capitalized to the capitalizable array. I use a similar code to upcase all Strings in certain models just to keep data clean an consistent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download