has_and_belongs_to_many relationship not associating both ways

感情迁移 提交于 2020-01-03 05:50:11

问题


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?


回答1:


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



回答2:


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?



来源:https://stackoverflow.com/questions/6197135/has-and-belongs-to-many-relationship-not-associating-both-ways

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!