为什么 Rails 4 中的连接表会出现未知主键异常? [英] Why do I get an Unknown Primary Key exception for a join table in Rails 4?

查看:13
本文介绍了为什么 Rails 4 中的连接表会出现未知主键异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我的模型:

class Product
  has_many :line_items
  has_many :orders, :through => :line_items
end

class LineItem 
  belongs_to :order
  belongs_to :product
end

class Order
    has_many :line_items
    has_many :products, :through => :line_items
end

来自 schema.rb:

From schema.rb:

  create_table "line_items", id: false, force: true do |t|
    t.integer  "order_id"
    t.integer  "product_id"
    t.integer  "quantity"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

我刚刚升级到 Rails 4,我的连接表停止工作.如果我执行 @order.line_items,它会抛出异常模型 LineItem 中表 line_items 的未知主键".@order.products 按预期工作.

I just upgraded to Rails 4, and my join table stopped working. If I do @order.line_items, it throws the exception "Unknown primary key for table line_items in model LineItem." @order.products works as expected.

我尝试删除并重新创建 line_items 表,并尝试安装 protected_attributes gem,但没有任何改变.

I have tried dropping and recreating the line_items table, and I have tried installing the protected_attributes gem, but nothing changed.

这是跟踪.

推荐答案

在模型中添加以下内容:

In model add the following:

self.primary_key = [:order_id, :product_id]

而且我认为确保在这些列上有一个 index 是明智的.

and I think it would be wise to ensure that there's an index on those columns.

您可以通过以下迁移创建一个:

You may create one with following migration:

add_index :line_items, [:order_id, :product_id]

这篇关于为什么 Rails 4 中的连接表会出现未知主键异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆