Prometheus
Prometheus

Reputation: 889

How to create a many to many relation in Rails

So currently i have in a app:

class Post < ApplicationRecord
 belongs_to :category
end

and

class Category < ApplicationRecord
    has_many :posts
end

which works fine as expected. However, i need to add multiple categories to a post . I thought about using has_many_and_belongs_to for each of them to acquire this but some trouble implementing this. It seems like a need to add an join table? If so, how would one look like with the setup shown above?

Any ideas?

I appreciate any input! Thanks in advance!

Upvotes: 0

Views: 76

Answers (2)

Pramod Shinde
Pramod Shinde

Reputation: 1892

Alternatively you can use has_many :through to have more control over a join table.

Advantages of using :through for many to many relationships

  • With has_many :through relationship you can have a model which will allow you to add validation, callbacks.
  • If you initially take some extra efforts to setup many to many relationship using through it can save a lot of time and headache in future
  • What if in future you want save the more information on join table like some custom sort, information about how the tables are associated which will not be allowed with has_and_belongs_to_many

Example

class Post < ApplicationRecord
  has_many :categories, through: :post_categories
  has_many :post_categories   
end

class Category < ApplicationRecord
  has_many :posts, through: :post_categories
  has_many :post_categories   
end

Adding relationship model with rails generator command

rails g model post_category category_id:integer post_id:integer custom:text 

class PostCategory < ApplicationRecord
  belongs_to :category
  belongs_to :post
end

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51151

The table should be named categories_posts (categories comes first because of alphabetical sequence) and contain post_id and category_id integer columns (indexed, most probably). The it's as simple as:

class Post < ApplicationRecord
  has_and_belongs_to_many :categories
end

class Category < ApplicationRecord
  has_and_belongs_to_many :posts
end

You can create join table adding migration using:

rails g migration CreateJoinTableCategoryPost category post

Upvotes: 2

Related Questions