ruby-on-railsrubymoney-rails

Running into undefined method `price_cents'


Have added money-rails gem to my app.

Migrated its column to my model Item

Migration

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

Model Item

class Item < ApplicationRecord
  belongs_to :invoice

  validates_numericality_of :unit_price, :quantity 

  monetize :price_cents

end

Schema

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

This is the error that I'm running into

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

Not sure how to resolve this.

EDIT

Ok, I dropped the price column, and have added it back as price_cents column as integer ...

However, should it be this in the schema:

t.integer "price_cents" ..

OR

t.monetize "price_cents"


Solution

  • The name of your column needs to be price_cents not price.

    The type of your column needs to be integer.

    I think you tried to copy

    add_money :products, :price
    

    but you used add_column instead of add_money.

    I used this gem recently but the add_money helper was undefined so I used

    add_column :items, :price_cents, :integer
    

    I don't think it will work with a money column type