Rails 中的多对多关系

发布于 2024-09-12 16:35:37 字数 300 浏览 2 评论 0原文

我有两个模型想要与多点关系连接,但我希望该关系有自己的一些数据,例如到期日期或计数或类似的东西......

假设我有用户,组和一些 UsersInGroups 对象,其中用户和组都具有 has_many X, :through Y 关系。 UsersInGroups belongs_to 一个用户和一个组,但也有一个 join_date 显示用户加入该组的时间。

因此我可以使用 self.groups.A 从用户获取组变量,反之亦然,但如何获取 join_date 变量?

I have two models I want to connect with an m-to-m relationship, but I want the relationship to have some data of its own, such as a date due or a count or something like that...

Suppose I have Users, Groups, and some UsersInGroups object, where users and groups both have a has_many X, :through Y relationship. UsersInGroups belongs_to a user and a group, but also has a join_date that shows when a user joined the group.

so I can use self.groups.A to get Group variables from User and vice versa, but how do I get at the join_date variable?

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

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

发布评论

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

评论(1

雪若未夕 2024-09-19 16:35:37

在多对多关系中,如果用户可以有多个组,并且您执行 aUser.user_in_groups,它将返回组的数组(这将是代表它们的模型类的实例)。您可以迭代其中的每一个并获取每个的 join_date ,或者通过索引到数组: aUser.user_in_groups[0].join_date

如果您只想要一个连接日期数组或其他内容,我会研究 Ruby 收集方法。

迭代:

aUser.users_in_groups.each do |group|
  group.join_date
end

In a many to many relationship, if a User can have many groups, and you do aUser.user_in_groups, it will return an array of the groups (which will be an instance of the model class representing them). You can iterate over each of these and obtain the join_date on each one, or by indexing into the array: aUser.user_in_groups[0].join_date

If you just want an array of join dates or something, I would look into the Ruby collect method.

Iteration:

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