如何在活动记录,rails 5中返回嵌套关联的所有记录

时间:2018-01-12 18:51:25

标签: ruby-on-rails activerecord ruby-on-rails-5

我正在努力找出嵌套关联上正确的活动记录查询。我试图让所有属于包含具有特定ID的pod的社区的用户。

举个例子,你可能有一个属于三个不同社区的pod,它们都有自己的成员列表(其中一些可能在社区中相同)。鉴于该pod的ID,我想拥有一个属于所有pod社区的所有相关成员的唯一列表。

class Pod
    has_many :pod_communities
    has_many :communities, through: :pod_communities
end

class Community
    has_many :pod_communities, dependent: :delete_all
    has_many :pods, through: :pod_communities

    has_many :community_members, dependent: :delete_all
    has_many :members, through: :community_members, class_name: "User", foreign_key: "user_id"
end

class User
    has_many :community_members, dependent: :delete_all
    has_many :communities, through: :community_members
end

1 个答案:

答案 0 :(得分:1)

请尝试以下代码

class Pod
  has_many :pod_communities
  has_many :communities, through: :pod_communities
  has_many :members, through: :communities  
end

Pod.first.members#将为属于与POD 1关联的任何社区的所有用户提供