lal*_*ala 12 activerecord ruby-on-rails exception jointable ruby-on-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
Run Code Online (Sandbox Code Playgroud)
来自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
Run Code Online (Sandbox Code Playgroud)
我刚刚升级到Rails 4,我的连接表停止工作.如果我这样做@order.line_items,它会抛出异常"模型LineItem中表line_items的未知主键".@order.products按预期工作.
我已经尝试删除并重新创建line_items表,我已经尝试安装protected_attributes gem,但没有任何改变.
这是痕迹.
Mik*_*del 16
在模型添加
self.primary_key = [:order_id, :product_id]
Run Code Online (Sandbox Code Playgroud)
我认为确保这些列上有索引是明智的.您可以使用以下迁移创建一个
add_index :line_items, [:order_id, :product_id]
Run Code Online (Sandbox Code Playgroud)
将id: false在原来的模式表明,没有id在表中的字段.Rails 4添加了一个create_join_table辅助方法,该方法创建没有id字段的表,并将其用于JoinTable名称中的任何迁移.
我可以想象你使用Rails 4而不是使用Rails 3获得不同结果的唯一方法就是重新生成迁移并JoinTable在名称中进行迁移.你还有Rails 3的架构吗?注意它id: false对于连接表来说会很有趣.
至于primary_key,你可以将主键设置为数组但后来不起作用的原因是因为该primary_key=方法盲目地将其参数转换为https://github.com/rails/rails/的第115行的字符串BLOB/a0dfd84440f28d2862b7eb7ea340ca28d98fb23f/ActiveRecord的/ lib目录/ active_record/attribute_methods/primary_key.rb#L115
另请参见/sf/answers/1401122411/及其链接.