2017-05-26 144 views
0

初始化貨幣化領域採取以下車型爲例:錢軌道:不0

class Product < ApplicationRecord 
    monetize :price_cents, numericality: { greater_than_or_equal_to: 0 } 
    … 
} 

這種模式

create_table "products", id: :serial, force: :cascade do |t| 
    t.integer "price_cents", null: false 
    … 
end 

當我創建一個新的Product有零price而不是值爲零我得到一個值爲0的Money對象。對我的用例不合意,因爲我寧願將空值設置爲顯式而非隱式設置。

設置在config.amount_columndefault:nil只給我上初始化所期望的行爲,但隨後price得到,如果Productprice更新仍設置爲無設置爲0 Money對象。

如何阻止此行爲?

+0

不應該是't.integer「price_cents」,null:true'? – everyman

+0

對,當我爲了簡潔而修改示例時犯了一個錯誤。它實際上只是'price_cents'。 – ESWAT

回答

0

你只需要刪除null: false選項。

+0

我仍然想爲'pirce_cents'強制執行非空值,我只是不希望由那個始終使該值不爲空的gem強制執行。 – ESWAT

+0

好吧,現在這是令人困惑的......凡事'貨幣'對象來自哪個寶石你使用? –

+0

我明白了......你使用'monetize' gem ..好..如果我理解你的擔憂,你想'錢'是'無',在這種情況下,如果你認爲實際上,'錢'不能' nil',但有些值至少爲0 ..如果你仍然希望它爲零,你可以有一個像'before_save'這樣的回調,你可以根據你的需求修改'money'並將其設置爲相應的'attribute'。 –