I have 2 models “users” and “events” and I used a has_many :through definition to define a many to many relationship between users and events. Each user can belong to 0 or many events and each event can have 0 or many users associated with it.
I know when I have a has_many and belongs_to relationship, I can simply do user.events.create(arg) and rails knows that the event is associated with that given user. However, when it is many to many, how do I associate them? How do I say user X now belongs to event A and user Y belongs to event A and user X also belongs to event B. Then, additionally, how would I destroy that relationship if I wanted?
Since neither the event nor the user only belongs to a single user/event…how would I define the relationship after a user instance and event instance are already created?
So…I guess i’m asking if this works:
@user = User.create(args)
@event = Event.create(args)
@user.events << @event
does this automagically associate the user with the event I just added to the user? It seems to work but then when I try this:
@user2 = User.create(args)
@user2.events << @event
this doesn’t seem to associate @user2 with that specific event but it associates the event with @user2. I did:
@event.users
and only @user was listed…not @user2 as well.
Check out the rails guide on associations. Specifically section 4.3 has_many Association Reference
It looks like the method you’re looking for is @customer.orders << @order1. In your case, with @user and @event, you’ll want to do the following:
and the correct associations will be created.