Rails 多态关联
我很难掌握 Rails 中的多态关联。我有两个模型,组和用户。
用户需要属于一个组,但组可以有多个用户和多个组。我需要我的群体像一棵树,我认为祖先宝石应该有所帮助,但我还没有尝试过。
似乎我需要某种具有 user_id 和 group_id 的加入模型,Membership。然后我可以做一个 has_many :through 将用户与组关联起来,但是我如何让它也有很多组呢?会员资格是多态模型吗?
谢谢!
安迪
I'm having a difficult time grasping polymorphic associations in Rails. I have two models, Group and User.
A User needs to belong to a group, but a Group can have_many users AND have_many groups. I need my groups to be like a tree, which I think the Ancestry gem should help, but I haven't tried yet.
Seems like I would need some kind of join model, Membership, that has a user_id and a group_id. Then I could do a has_many :through to relate users to groups, but how would I get it to have many groups as well? Would the Membership be the polymorphic model?
Thanks!
Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是多态关联。多态关联是超越类类型的关联,例如属于人和狗类的图像类。
您正在谈论单表继承,其中组可以属于另一个组并具有其他组。像下面这样的东西就是您正在寻找的东西。
这只是空中代码,可能需要一些调整
This is not a polymorphic association. A polymorphic association is an association that transcends class types, such as a image class belonging to people and dogs class.
You are talking about Single Table Inheritance where Groups can belong to another group and have other groups. Something like what is below is what you are looking for.
This is just air code, might need some tweaks
是的,你基本上已经明白了。您的会员资格模型需要以下字段:
group_id 是“成员”所属的组。 member_id 是个人或组的 ID,member_type 是“个人”或“组”。
成员资格将具有以下关联:
然后您的用户和组类将具有类似的内容
Yes, you've basically got it. Your Membership model would need the following fields:
group_id is the Group the "member" belongs to. member_id would be the id of a Person or Group, and member_type would be 'Person' or 'Group'.
Membership would have the following association:
Then your User and Group classes would have something like
我认为祖先是正确的答案。我用过一个更老的,acts_as_tree,它很有帮助。现在开始一个新项目我会使用 Ancestry。正如其他答案所建议的那样,您可以不这样做,但您将无法获得 Ancestry 为您提供的所有免费方法。
I think Ancestry is the right answer. I've used a much older one, acts_as_tree, and it was helpful. Starting a new project now I'd use Ancestry. You can do it without that as other answers have suggested but you won't get all the free methods Ancestry gives you.