簡體   English   中英

如何使用Rails Money gem而不是美分處理美元金額?

[英]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,
  1. 如何處理美元金額? 即我想將total_cents的amount_cents添加到tax_cents中。 2.60而不是amount_cents:260,
  2. 我需要添加一個“ composed_of”嗎?
  3. 另外,為什么在命名中使用“分”? 我認為應該刪除它,因為模糊的文檔指出:

在這種情況下,通過從列名稱中刪除_cents后綴來自動創建money屬性的名稱。

  1. 美分發行

money gem以美分形式存儲金額,並且在表定義中,兩個字段將定義屬性。

對於例如,考慮具有財產amountTransaction schema.rb您將找到2個字段: amount_centsamount_currency

因此,現在您將擁有一個帶有貨幣對象的transaction.amount 使用金錢對象,您可以:

  • 使用money_rails 幫助程序中的humanized_money @money_object顯示格式化的金額
  • 您可以進行加,減,甚至轉換為其他貨幣的操作

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.amountClient類訪問amount屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM