Reputation: 8631
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.
Upvotes: 0
Views: 181
Reputation:
This is how I do it:
class User
has_many :events, :through => :user_event_associations
has_many :user_event_associations
class Event
has_many :users, :through => :user_event_associations
has_many :user_event_associations
class UserEventAssociation
belongs_to :user
belongs_to :event
If you do this you can do
some_user_object.events << some_event_object
and then if you reload the some_event_object
you'll see the relationship there as well. Please note that user_event_associations is the join table and exists as a real table and model with only those two lines above. I don't ever use that table--it's an under-the-covers thing to support the many to many association.
As for the destroy behavior, you might take a peek at dependent => destroy
Upvotes: 0
Reputation: 4027
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:
@user.events << @event
and the correct associations will be created.
Upvotes: 0