2

I have the following class and I want to monetize a couple of its fields using the money-rails gem.

class LineItem < ActiveRecord::Base
  monetize :unit_price_cents
  monetize :total_cents
end

This is how the schema looks:

create_table "line_items", force: :cascade do |t|                                                             
   t.integer  "invoice_id"                                                                                     
   t.float    "quantity"                                                                                       
   t.string   "unit_type"                                                                                      
   t.string   "description"                                                                                    
   t.datetime "created_at",       null: false                                                                  
   t.datetime "updated_at",       null: false
   t.integer  "unit_price_cents", null: false                                                                                                                               
   t.integer  "total_cents",      null: false                                                                  
end 

For some reason I get undefined method 'unit_price' for #<LineItem:0x007ffb7881eb80> unless I add aliasing to the monetized fields:

monetize :unit_price_cents, as: :unit_price
8vius
  • 5,786
  • 14
  • 74
  • 136

1 Answers1

1

As per Money Rails gem documentation, the :as is not necessary in this case. It should only be used if you are using another db column name, or you prefer another name for the money attribute.

In your case since your db column name is already in the format the gem expects. You only have to do

monetize :unit_price_cents

To then call unit_price on you LineItem instance to get the monetized object

@lineitem = LineItem.first
@lineitem.unit_price
Joseph N.
  • 2,437
  • 1
  • 25
  • 31