为什么我会在轨道4连接表一个未知的主键异常? [英] Why do I get an Unknown Primary Key exception for a join table in 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。 <$ C C $> @ 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宝石,但什么都没有改变。
I have tried dropping and recreating the line_items table, and I have tried installing the protected_attributes gem, but nothing changed.
下面是跟踪。
推荐答案
在模型中加入
self.primary_key = [:order_id, :product_id]
,我认为这将是明智的,以确保有对这些列的索引。您可以创建具有以下迁移一个
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]
这篇关于为什么我会在轨道4连接表一个未知的主键异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!