简体   繁体   English

Rails多态协会

[英]Rails Polymorphic Association

I'm having a difficult time grasping polymorphic associations in Rails. 我在抓住Rails中的多态关联时遇到了困难。 I have two models, Group and User. 我有两个模型,Group和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. 我需要我的团队就像一棵树,我认为Ancestry宝石应该有所帮助,但我还没有尝试过。

Seems like I would need some kind of join model, Membership, that has a user_id and a group_id. 好像我需要某种具有user_id和group_id的连接模型,Membership。 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? 然后我可以做一个has_many:通过将用户与群组联系起来,但我怎么能让它拥有多个群组呢? Would the Membership be the polymorphic model? 会员资格会是多态模型吗?

Thanks! 谢谢!

Andy 安迪

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 这只是空中代码,可能需要一些调整

class User
  belongs_to :group
end

class Group
  has_many :users
  has_many :sub_groups, :class => "Group", :foreign_key => :parent_group_id
  belongs_to :parent_group, :class => "Group", :foreign_key => :parent_group_id
end

Yes, you've basically got it. 是的,你基本上得到了它。 Your Membership model would need the following fields: 您的会员资格模型需要以下字段:

group_id
member_id
member_type

group_id is the Group the "member" belongs to. group_id是“成员”所属的组。 member_id would be the id of a Person or Group, and member_type would be 'Person' or 'Group'. member_id将是Person或Group的id,member_type将是'Person'或'Group'。

Membership would have the following association: 会员资格如下:

class Member < ActiveRecord::Base
  belongs_to :member, :polymorphic => true
end

Then your User and Group classes would have something like 那么你的用户和组类就会有类似的东西

has_many :memberships, :as => :member

Check this link out: Rails model relationships . 检查此链接: Rails模型关系 I found it very helpful in nailing down the various relationships rails supports easily and well. 我发现它非常有助于确定导轨支持的各种关系。

EDIT: fixed URL. 编辑:固定的URL。 sorry. 抱歉。

I think Ancestry is the right answer. 我认为祖先是正确的答案。 I've used a much older one, acts_as_tree, and it was helpful. 我使用了一个更老的,acts_as_tree,它很有帮助。 Starting a new project now I'd use Ancestry. 现在开始一个新项目我会使用Ancestry。 You can do it without that as other answers have suggested but you won't get all the free methods Ancestry gives you. 你可以在没有其他答案的情况下做到这一点,但你不会得到Ancestry给你的所有免费方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM