Home How to return all records on nested association in active record, rails 5
Reply: 1

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

Lorenz
1#
Lorenz Published in 2018-01-12 18:51:24Z

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
Nimish Gupta
2#
Nimish Gupta Reply to 2018-01-12 19:05:39Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.345434 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO