How to create records in has_many through association

Hi All,

I have two models (User and Event) with multiple has_many through associations, where my current association is by the below logic:

  1. User can participate in many events through EventGroup
  2. Event has many users through EventGroup
  3. User can like many events through Eventgroup
  4. Event has many user likes through Eventgroup Model:
class User
 has_many : event_groups
has_many :events,:through => : event_groups
has_many :event_likes,:through => :event_groups,:class_name => "Event"
end

class Event
  has_many :  event_groups
has_many :users,:through => :  event_groups
has_many :user_likes,:through => :event_groups,:class_name => "User"
end

class EventGroup
  belongs_to :  user
belongs_to :event
  belongs_to :user_like,:class_name => "User"
  belongs_to :event_like,:class_name => "Event"
end

EventGroup columns:

user_id
event_id
user_like_id
event_like_id

After setting up the association I tried to create the association record with the below code:

user = User.first
user.event_likes << Event.first user.save

This is working fine and I can able to get the events liked by that user as user.event_likes.

But I am not able to get the User records by event.user_likes, so I checked my eventgroup record. It has the nil value for user_like_id.

#<EventGroup id: 24, event_id: 1, user_id: 2,event_like_id: 1, user_like_id: nil>

Let me know the proper way to do this.

regards, Loganathan Mob: +91 7760780741 | +91 9944414388 Skype: loganathan.sellappa ViewMe

Hey Loganathan,

I think the problem is that you trying to model 2 different things throught the same joint model and that does not work, because on the join model you modelling something with 2 different values of events and of users, so you can have values, user_id = 1, event_id = 1, user_like_id = 2, event_id = 2, this represents 2 different users and 2 different events. so basically you have to create to joint models.

class User

has_many :event_appreciations

has_many :event_attendings

has_many :events, :through => :event_attendings

has_many :event_likes, :through => :event_groups, :class_name => “Event”

end

class Event

has_many :event_appreciations

has_many :event_attendings

has_many :users,:through => :event_appreciations

has_many :user_likes, :through => :event_attendings, :class_name => “User”

end

class EventAppreciation

belongs_to :user

belongs_to :event

end

class EventAttending

belongs_to :user

belongs_to :event

end

this should solve your problem,

All the best,

Andre