2016-05-31 38 views
0

試圖在rails 4中重構has_and_belongs_to_many關聯以添加額外的列,但是在自引用has_many_through上掙扎。如何使用rails has_many通過關聯來防止'未知列'錯誤

一個項目可以包含很多組件。組件實際上只是項目,因此可以擁有自己的組件;

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',所以我在哪裏錯誤地定義了它?那麼,我如何讓這個協會起作用呢?

回答

0

時,會出現你的錯誤,因爲軌爲component_item_id列搜索表items,但你有沒有這樣的專欄中,我相信你應該創造itembelongs_to關係到它,看來你有模式之間只是錯誤的關係基本和模式,所以對於目前的方案,您定義我建議機型:

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表命名type額外的字符串字段。

+0

錯誤狀態表明它正在查找'items'表中的列,而不是'component_items'。重命名該列不會解決問題。指定外鍵不會改變任何內容。 – mvanio

+1

爲什麼需要'type'? – mvanio

相關問題