[英]How do I work with dollar amounts not cents with Rails Money gem?
我正在嘗試使錢軌寶石正常工作,但是我遇到了問題...
其他類似的stackoverflow問題已有6年歷史了。
這是我在以下產品上有相應專欄的產品:
class Transactions < ActiveRecord::Base
belongs_to :user, optional: true
validates :trans_id, uniqueness: true
monetize :price_cents
end
我的Gemfile中包含了gem,並成功運行了bundle install。
當我創建一個新項目並用撬撬看它時,
create(vendor:"foo",amount:2.6,trans_id:'123cccc')
id: nil,
vendor: "foo",
amount_cents: 260,
amount_currency: "USD",
trans_id: "123cccc",
tax_cents: 150,
total_cents:410,
在這種情況下,通過從列名稱中刪除_cents后綴來自動創建money屬性的名稱。
money
gem以美分形式存儲金額,並且在表定義中,兩個字段將定義屬性。
對於例如,考慮具有財產amount
的Transaction
。 在schema.rb
您將找到2個字段: amount_cents
和amount_currency
。
因此,現在您將擁有一個帶有貨幣對象的transaction.amount
。 使用金錢對象,您可以:
3)'自動屬性'
正在遷移:
class AddAmountToClient < ActiveRecord::Migration
def change
add_monetize :clients, :amount
end
end
遷移后,您可以在schema.rb中找到
create_table "clients", force: :cascade do |t|
t.integer "amount_cents", limit: 8, default: 0, null: false
t.string "amount_currency", default: "USD", null: false
end
attribute is created automagically by removing the _cents
可以attribute is created automagically by removing the _cents
,這意味着您可以使用具有money對象的client.amount
從Client
類訪問amount
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.