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

问题描述 投票:0回答:1

我正试图让money-rails 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. 我如何以美元金额使用它?即我想将amount_cents添加到total_cents的tax_cents中。金额2.60而不是amount_cents:260,
  2. 我需要添加'composed_of'吗?
  3. 另外,为什么命名是分?我认为它应该被移除,因为模糊的文件说明:

在这种情况下,通过从列名中删除_cents后缀来自动创建money属性的名称。

ruby-on-rails ruby money-rails
1个回答
0
投票
  1. 美分问题

money gem以美分存储金额,在表定义中,2个字段将定义属性。

例如,考虑在amount拥有Transaction财产。在schema.rb,你会发现2个领域:amount_centsamount_currency

那么,现在你将拥有一个带钱币对象的transaction.amount。有钱对象你可以:

  • 使用money_rails helpers中的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的含义是什么意思,你可以从amount类访问Client属性,client.amount有钱对象。

© www.soinside.com 2019 - 2024. All rights reserved.