coolesting
coolesting

Reputation: 1451

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 words, 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.

Upvotes: 0

Views: 133

Answers (1)

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47913

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

Upvotes: 1

Related Questions