我连接了模型product
和cart_item
。
add_reference :cart_items, :product, null: false, foreign_key: true
schema.rb:
create_table "cart_items", force: :cascade do |t|
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.bigint "product_id", null: false
t.bigint "cart_id", null: false
t.index ["cart_id"], name: "index_cart_items_on_cart_id"
t.index ["product_id"], name: "index_cart_items_on_product_id"
end
但是当我尝试创建并引用模型属性时,出现错误:
undefined method `product' for #<CartItem:0x0000563873ac8a30>
Did you mean? product_id
a = CartItem.new
a.product_id = 5
a.cart_id = 1
a.save
a.product.title
#NoMethodError (undefined method `product' for #<CartItem:0x00007ff110f96b50>) Did you mean? product_id
a.product_id #=> 5
答案 0 :(得分:1)
根据您共享的信息,我相信您只是在模型类中添加了Db迁移,但未添加ORM(ActiveRecord)关联。
class CartItem
...
belongs_to :product #Hope you have a model named 'Product'
...
end
我相信添加以上行应该可以解决该错误。