Reputation: 8631
i setup a relationship using has_and_belongs_to_many to associate users and events. Then I try this:
user = User.find(1)
event = Event.find(1
)
both of these are not currently associated...then I try to associate them by doing:
user.events << event
this action works...however, they don't associate correctly for each other:
user.events lists the event correctly for this user...but event.users does not have that user associated with it.
how do I make it so that when I associate one with the other (either the event with user or user with event)...it automatically associates the other way?
Upvotes: 0
Views: 331
Reputation: 50057
Assuming your links are setup correctly, you can test this:
user.events << event
event.reload.users
This will explicitly reload the data from the database, instead of using the locally cached version. If you have ever accessed the association, it will not look it up in the database anymore, unless you explicitly ask it.
Does that help?
Upvotes: 0
Reputation: 7188
Is the has_and_belongs_to_many
present in both models? It sounds like it is not, whereas it should be:
# models/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :events
end
# models/event.rb
class Event < ActiveRecord::Base
has_and_belongs_to_many :users
end
Upvotes: 1