2

我有以下课程,我想monetize使用money-railsgem 来处理它的几个字段。

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

这是架构的外观:

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 

出于某种原因,undefined method 'unit_price' for #<LineItem:0x007ffb7881eb80> 除非我在货币化字段中添加别名,否则我会得到:

monetize :unit_price_cents, as: :unit_price
4

1 回答 1

1

根据 Money Rails gem文档:as在这种情况下不需要。仅当您使用另一个数据库列名称,或者您更喜欢货币属性的另一个名称时才应该使用它。

在您的情况下,因为您的 db 列名已经是 gem 期望的格式。你只需要做

monetize :unit_price_cents

然后调用unit_price您的 LineItem 实例以获取货币化对象

@lineitem = LineItem.first
@lineitem.unit_price
于 2021-01-20T13:54:24.810 回答