So I have a form where users can input a price. I\'m trying to make a before_validation that normalizes the data, clipping the $ if the user puts it.
before_val
One way is to override the mechanism on the model that sets the price, like this:
def price=(val)
write_attribute :price, val.to_s.gsub(/\D/, '').to_i
end
So when you do @model.price = whatever
, it will go to this method instead of the rails default attribute writer. Then you can convert the number and use write_attribute
to do the actual writing (you have to do it this way because the standard price=
is now this method!).
I like this method best, but for reference another way to do it is in your controller before assigning it to the model. The parameter comes in as a string, but the model is converting that string to a number, so work with the parameter directly. Something like this (just adapt it to your controller code):
def create
@model = Model.new(params[:model])
@model.price = params[:model][:price].gsub(/\D/, '').to_i
@model.save
end
For either solution, remove that before_validation
.