如何通过关联防止 'Unknown column' 与 rails has_many 的错误

How to prevent 'Unknown column' error with rails has_many through association

正在尝试重构 rails 4 中的 has_and_belongs_to_many 关联以添加额外的列,但正在努力解决自我引用 has_many_through

一个项目可以由许多组件组成。组件实际上只是项目,因此可以有自己的组件;

class Item < ActiveRecord::Base
  has_many :components, through: :component_items
  has_many :component_items
end

class Component < ActiveRecord::Base
  has_many :items, through: :component_items
  has_many :component_items
  self.table_name ="Items"
end

class ComponentItem < ActiveRecord::Base
  has_many :items
  has_many :components
end

模式看起来像...

create_table "component_items", force: :cascade do |t|
  t.integer "item_id",      limit: 4, null: false
  t.integer "component_id", limit: 4, null: false
end

create_table "items", force: :cascade do |t|
  t.string   "sku",    limit: 255
  t.decimal  "height", precision: 6, scale: 2
  t.decimal  "width",  precision: 6, scale: 2
  t.decimal  "depth",  precision: 6, scale: 2
end

然后

i=Item.first
i.components

我得到:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'items.component_item_id' in 'on clause': SELECT items.* FROM items INNER JOIN component_items ON items.component_item_id = component_items.id WHERE component_items.item_id = 87675

我不需要列'items.component_item_id',所以我在哪里错误地定义了它?那么,我该如何让这个协会发挥作用呢?

出现您的错误是因为 rails 在 table items 中搜索列 component_item_id,但您没有这样的列,我相信您应该创建 belongs_to 与它的 item 关系,但是 似乎你在模式和模型之间的关系是错误的,所以对于你定义的当前方案,我建议模型:

class Item < ActiveRecord::Base
  has_many :components, through: :component_items
  has_many :component_items
end

class Component < Item
  has_many :items, through: :component_items
  has_many :component_items
end

class ComponentItem < ActiveRecord::Base
  belongs_to :item
  belongs_to :component
end

注意 这需要在 items table.

中添加一个名为 type 的额外字符串字段