Ruby on rails tutorials

Rails many-to-many association tutorial

March 23rd, 2011

Has and belongs to many

If you just need to set a simple many-to-many relationship the easiest way to do this is with has_and_belongs_to_many. Here is how your models should look like.

1
2
3
4
5
6
7
class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags
end
 
class Tag < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

This association is supported by an additional database table that will store post_id and tag_id for each relationship. This table should be called posts_tags and it will not be created for you, so you will have to create your own migration.

has and belongs to many er-model
Read the rest of this entry »