Lorenz
Lorenz

Reputation: 775

How to return all records on nested association in active record, rails 5

I'm struggling to figure out the proper active record query on a nested association. I'm trying to get all users that belong to any communities that contain a pod with a particular id.

So as an example, you might have a pod which belongs to three different communities which all have their own list of members (some of which might be the same across communities). Given that pod's id, I want to have a unique list of all the associated members that belong to all of the pod's communities.

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

Upvotes: 0

Views: 653

Answers (1)

Nimish Gupta
Nimish Gupta

Reputation: 3175

Please try the following code

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

Pod.first.members # Will give all the users which belongs to any community which is associated with POD 1

Upvotes: 1

Related Questions