开发者

Associating multiple models with a model

let's looking my database schema first, this is a simple structure of database tables as the following.

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) 

The data row of table tag_item will be like this.

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

The item_type and item_id field in tag_item table as the related table name and table primary key id, in other word开发者_C百科s, i want to make use of the tag as the keyword to associating all of tables. So, how to write the code in individual model class for associating each other with tag. How to design the association in class model with the way of rails.

thanks in advance.


You can use has_many :through to implement the associations:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜