0

已将money-railsgem 添加到我的应用程序中。

将其列迁移到我的模型Item

移民

class AddPriceToItems < ActiveRecord::Migration[5.0]
  def change
    add_column :items, :price, :money
  end
end

模型项目

class Item < ApplicationRecord
  belongs_to :invoice

  validates_numericality_of :unit_price, :quantity 

  monetize :price_cents

end

架构

ActiveRecord::Schema.define(version: 20170223211329) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "invoices", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "items", force: :cascade do |t|
    t.decimal  "unit_price", precision: 10, scale: 2
    t.integer  "quantity"
    t.integer  "invoice_id"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.money    "price",                     scale: 2
    t.index ["invoice_id"], name: "index_items_on_invoice_id", using: :btree
  end

  add_foreign_key "items", "invoices"
end

这是我遇到的错误

undefined method `price_cents' for #<Item:0x007f9f6b366ae8>
Did you mean?  price_cents=

不知道如何解决这个问题。

编辑

好的,我删除了价格列,并将其添加回 price_cents 列作为整数...

但是,在架构中应该是这样的:

t.integer "price_cents"..

或者

t.monetize "price_cents"

4

3 回答 3

1

您的列的名称必须price_cents不是price.

您的列的类型必须是integer.

我想你试图复制

add_money :products, :price

但你用add_column而不是add_money.

我最近使用了这个 gem,但是add_money助手是未定义的,所以我使用了

add_column :items, :price_cents, :integer

我认为它不适用于money列类型

于 2017-02-24T19:47:16.863 回答
1

如果您试图确保您正在添加/相乘的金额不会给出不准确的总和或乘积(例如 14.099 美元 ..),那么您可以考虑走这条路:

1) 生成您的 Items 模型时,请使用此 price:monetize

2) 在您的迁移文件中,这将反映为: t.monetize :price

3) 运行后rails db:migrate,这将在您的 ItemsTable 中生成两列:第一列将是price_cents( 以美分为单位的项目金额,(例如 1000 = $10) 第二列将是 price_currency (例如 $),默认值是 schema.rb 中的 USD

t.integer "price_cents", default: 0, null: false t.string "price_currency", default: "USD", null: false

于 2017-02-24T21:44:06.957 回答
0

您的模型应该有一个整数(不是货币类型)price_cents 列,而不是价格。传递给货币化的符号应该是该列。见这里:https ://github.com/RubyMoney/money-rails#usage-example

于 2017-02-24T19:45:28.890 回答