Giacomo Delfini
Giacomo Delfini

Reputation: 61

Ruby on Rails multiple many to many relations between two models

I have two relations m:n type that links a table Users with a table Videos. I create it by these line command:

rails generate migration users_comments_videos
rails generate migration users_views_videos

In the files user.rb and videos.rb I respectively added the instructions:

has_and_belongs_to_many :users
has_and_belongs_to_many :videos

Are these two instructions valid for for both of the relations that I created?

Upvotes: 3

Views: 845

Answers (1)

Anil
Anil

Reputation: 3919

Pick different association names and then specify the model.

user.rb

class User
  has_many :comments
  has_many :views
  has_many :comment_videos, :through => :comments, :source => 'Video'
  has_many :view_videos, :through => :views, :source => 'Video'
end

video.rb

class Video
  has_many :comments
  has_many :views
  has_many :comment_users, :through => :comments, :source => 'User'
  has_many :view_users, :through => :views, :source => 'User'
end

Upvotes: 2

Related Questions