【问题标题】:Running into undefined method `price_cents'遇到未定义的方法“price_cents”
【发布时间】:2017-02-24 19:38:47
【问题描述】:

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

将其列迁移到我的模型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 列,并将其作为 price_cents 列添加为整数 ...

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

t.integer "price_cents"..

t.monetize "price_cents"

【问题讨论】:

    标签: ruby-on-rails ruby money-rails


    【解决方案1】:

    您的专栏名称必须是 price_cents 而不是 price

    您的列类型必须是integer

    我认为你试图复制

    add_money :products, :price
    

    但是你使用了add_column 而不是add_money

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

    add_column :items, :price_cents, :integer
    

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

    【讨论】:

    • ... 再次,换句话说,删除原始的price 列并将其添加回price_center 和整数...?我对自己的所作所为感到有些困惑……不知道我是怎么做到的
    • t.integer "price_cents"
    【解决方案2】:

    如果您试图确保您添加/相乘的金额不会给出不准确的总和或乘积(例如 $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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 换句话说,删除 Items 表中的当前列,并将其作为整数添加回来,全名为 price_cents?
      猜你喜欢
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多