0

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!

Jeffrey Hunter
  • 1,103
  • 2
  • 12
  • 19
  • Take a look at [this](http://stackoverflow.com/questions/1163032/rails-has-many-with-alias-name). Essentially, you can set up multiple associations (with different names) between the same two classes. – steve klein Jul 17 '15 at 20:59

1 Answers1

1
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

Sarcastic
  • 677
  • 5
  • 14
coorasse
  • 5,278
  • 1
  • 34
  • 45