Search code examples
ruby-on-railsmodelrails-activerecord

Rails / ActiveRecord: field normalization


I'm trying to remove the commas from a field in a model. I want the user to type a number, i.e. 10,000 and that number should be stored in the database as 10000. I was hoping that I could do some model-side normalization to remove the comma. I don't want to depend on the view or controller to properly format my data.

I tried:

before_validation :normalize

def normalize 
 self['thenumber'] = self['thenumber'].to_s.gsub(',','')
end

no worky.


Solution

  • The problem with doing it that way is that for a while, the non-normalized stuff will exist in the object; if you have code that works on the attributes before stuff gets normalised, then that will be a problem.

    You could define a setter:

    def thenumber=(value)
      # normalise stuff here, call write_attribute
    end
    

    Unfortunately I think a lot of the Rails form stuff writes the attributes directly, which is one of the reasons I don't tend to use it.

    Or you could normalise the params in the controller before you pass them through.