【问题标题】:How to return all records on nested association in active record, rails 5如何在活动记录中返回嵌套关联的所有记录,rails 5
【发布时间】:2018-01-12 18:51:24
【问题描述】:

我正在努力找出嵌套关联中正确的活动记录查询。我正在尝试获取属于包含具有特定 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

【问题讨论】:

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


    【解决方案1】:

    请尝试以下代码

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多