ruby on rails - Issue converting currency from string in before_validation callback -
i'm having issue stripping dollar signs , commas out of currency before validations run. reason value being set 0
when saved.
class property < activerecord::base before_validation :format_currency validates :street_name_1, presence: true validates :city, presence: true validates :state, presence: true validates :postal_code, presence: true validates :rate, presence: true, numericality: true private def format_currency self.rate = rate.to_s.gsub(/[^0-9\.]/, '').to_i # strip out non-numeric characters end end
when '$3,500'.to_s.gsub(/[^0-9\.]/, '').to_i
in rails console correctly returns "3500". rate
being passed in model form well.
for life of me can't figure out why it's not setting value on save. appreciated.
edit: needed override default setter , gsub when rate set due database column being integer.
def rate=(rate) write_attribute(:rate, rate.to_s.gsub(/[^0-9\.]/, '').to_i) end
since storing rate
column integer, , using rails, propose remove format_currency
method entirely. rails has method deal currencies already: number_to_currency
.
when want output price, simple use helper:
number_to_currency @property.rate
this gives greater flexibility too, since can localise , pass number of other options. have @ api.
edit, per op editing question:
if want save in format, why don't apply dollar sine in model?
before_save :set_rate def set_rate self.rate = "$#{rate}" end
Comments
Post a Comment