2011-08-21 129 views
0

讓我們先看看我的數據庫模式,這是一個數據庫表的簡單結構,如下所示。將多個模型與模型關聯

page table (id, title, description, link) 
post table (id, body) 
list table (id, name) 
user table (id, uname, upawd) 
tag table (id, name) 

tag_item (tag_id, item_id, item_type) 

tag_item的數據行會是這樣的。

tag_id item_id item_type  
1  1   page 
1  2   page 
1  1   post 
2  1   user 
3  1   list 

item_typetag_item表作爲相關的表名和表的主鍵ID item_id場,換句話說,我想利用標籤作爲關鍵字的所有表的關聯。 那麼,如何在單獨的模型類中編寫代碼來將對方與標籤相關聯。 如何使用rails的方式設計類模型中的關聯。

在此先感謝。

+0

你也有一個'type'表? – Behrang

+0

沒有'type'表,'type'字段在tag_item表中。該字段主要用於標記「page」之類的對象類型。 'post','user'等等。這意味着我上面的每個對象都有它的標籤,我們創建一個用於存儲所有標籤的標籤表,並且需要一個像'tag_item'這樣的表來關聯所有對象表和標籤表 – coolesting

+0

但是您也有'type_id'。你最好創建一個'type'(實際上在rails表中名字應該是複數,所以你需要'types')表,就像'types(id,name)'一樣,在你的'tag_items'表中引用它就像'tag_items(tag_id,type_id )'。 – Behrang

回答

1

您可以使用has_many :through來實現關聯:

class Type < ActiveRecord::Base 
    has_many :tag_items 
    has_many :tags, :through => :tag_items 
end 

class Tag < ActiveRecord::Base 
    has_many :tag_items 
    has_many :types, :through => :tag_items 
end