Search code examples
ruby-on-railsrubycallbackrails-activerecordmodels

Capitalizing more than one attribute in a Rails before_save method


I'd like to capitalize the first_name and last_name of my model instances using the before_save method. Of course I could do this:

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

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?


Solution

  • You could do something like this

    before_save :capitalize_attributes
    
    private
       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)
         end
       end
    

    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.