2

I have implemented the money-rails gem to enables prices on an Item model.

Right now I parse a string with the price before creating a new Item in the items_controller.rb, like this:

@item = Item.find_or_create_by_link!(params[:item][:link]) do |c|
    c.assign_attributes(params[:item])
    c.price = params[:item][:price].to_money unless params[:item][:price].nil?
end

However, I was wondering if there is a more 'correct' way of automatically parsing the string before saving it to the model. I was trying a before_save filter but couldn't get it to work.

The price is stored in two columns in the Item model, price_cents and price_currency.

Daniel Friis
  • 444
  • 3
  • 23

1 Answers1

1

You could override the attribute writer in your Item model or even define a new instance method (as a virtual attribute) that performs all related logic. For example:

models/item.rb

...
def price=(price)
  money = price.to_money
  self.price_cents = money.fractional
  self.price_currency = money.currency.iso_code
end
Kostas Rousis
  • 5,918
  • 1
  • 33
  • 38