has_and_belongs_to_many 关系不双向关联

发布于 2024-11-11 12:05:29 字数 384 浏览 0 评论 0原文

我使用 has_and_belongs_to_many 设置关系来关联用户和事件。然后我尝试这个:)

user = User.find(1)
event = Event.find(1

两个当前都没有关联...然后我尝试通过执行以下操作来关联它们:

user.events << event

此操作有效...但是,它们彼此没有正确关联:

user.events 正确列出了事件对于此用户...但 event.users 没有与其关联的用户。

我该如何做到这一点,以便当我将一个与另一个关联时(事件与用户或用户与事件)......它会自动以另一种方式关联?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娇俏 2024-11-18 12:05:30

假设您的链接设置正确,您可以对此进行测试:

user.events << event
event.reload.users

这将显式地从数据库重新加载数据,而不是使用本地缓存的版本。如果您曾经访问过该关联,它将不再在数据库中查找它,除非您明确询问它。

这有帮助吗?

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?

九厘米的零° 2024-11-18 12:05:29

has_and_belongs_to_many 是否存在于两个模型中?听起来好像不是,但它 应该是:

# 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文