Rails 中的多对多关系
我有两个模型想要与多点关系连接,但我希望该关系有自己的一些数据,例如到期日期或计数或类似的东西......
假设我有用户,组和一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在多对多关系中,如果用户可以有多个组,并且您执行 aUser.user_in_groups,它将返回组的数组(这将是代表它们的模型类的实例)。您可以迭代其中的每一个并获取每个的 join_date ,或者通过索引到数组: aUser.user_in_groups[0].join_date
如果您只想要一个连接日期数组或其他内容,我会研究 Ruby 收集方法。
迭代:
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: