Jeffrey Hunter
Jeffrey Hunter

Reputation: 1163

How do I have multiple has_many to has_many relationship between two models?

I'm newer to Rails and have a problem with a model that has multiple relationships to another model. This is my current setup, and I can add events to the user through the UserEvents model. However, obviously I can't have the relationship called events twice...and this is where I am stumped.

class User < ActiveRecord::Base
  has_many :user_events
  has_many :events, :through => :user_events
  has_many :events, :through => :user_participating
end

class UserEvents < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class UserParticipating < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class Events < ActiveRecord::Base
  has_one :user_event
  has_one :user, :through => :user_events
  has_many :user_participating
  has_many :user, :through => :user_participating
end

There is definitely a good chance I am going about this all wrong, however, I have been at it for several hours and I don't seem to be getting anywhere. So, I figured I would ask. Thanks!

Upvotes: 0

Views: 675

Answers (1)

coorasse
coorasse

Reputation: 5528

class User < ActiveRecord::Base
  has_many :user_events
  has_many :user_participatings
  has_many :events, through: :user_events
  has_many :participating_events, through: :user_participatings, class_name: 'Event'
end

class UserEvents < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class UserParticipating < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class Events < ActiveRecord::Base
  has_one :user_event
  has_one :user, through: :user_events
  has_many :user_participatings
  has_many :participants, through: :user_participatings, source: :user
end

Even if I notice an event has_one user so I don't see why you need the UserEvent class

Upvotes: 1

Related Questions