Daniel Friis
Daniel Friis

Reputation: 484

Auto parse price with money-rails

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.

Upvotes: 2

Views: 510

Answers (1)

Kostas Rousis
Kostas Rousis

Reputation: 6088

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

Upvotes: 1

Related Questions