0

我正在尝试让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 添加到tax_cents for total_cents。金额 2.60 而不是 amount_cents: 260,
  2. 我需要添加“composed_of”吗?
  3. 另外,为什么命名中是“cent”?我认为它应该被删除,因为模糊的文档指出:

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

4

1 回答 1

0
  1. 美分问题

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

例如,考虑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意思是,这意味着您可以通过拥有金钱对象来访问类中的amount属性。Clientclient.amount

于 2018-03-05T09:18:43.763 回答