Search code examples
ruby-on-railsmodel-associationsruby-on-rails-4

How do I collect all the topics that are owned by the members of the groups I am a member of?


This may be tough for me to explain, so if it's not clear just let me know so I can edit as needed!

I have the following example:

class User < ActiveRecord::Base
  has_many :topics
  has_many :memberships
end

class Topic < ActiveRecord::Base
  belongs_to :user
end

#join model between User and Group
class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :members, :through => :memberships, :source => :user
  has_many :topics, :through => :members
end

The problem I'm having is that I am trying to create a feed (@feed_topics) of all topics that are owned by all the members of the groups I am a member of, and I'm driving myself a little nuts.

Should I try to make this happen using associations, or make an instance method in my User model that has some ActiveRecord/SQL to union all the groups' members' topics into one ActiveRecord::Relation object?

My goal is to write current_user.feed_topics in my controller's action.


Solution

  • Sorry for not explaining earlier! The idea was to utilize 'Nested has_many_through's in order to get to your feed topics. This concept is documented here under the heading 'Nested Associations': http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html. Let me know if this still is unclear (or if it doesn't work).

    class User < ActiveRecord::Base
      has_many :topics
      has_many :memberships
      has_many :groups, :through => :membership
      has_many :group_members, :through => :groups, :source => :member
      has_many :feed_topics, :through => :group_members, :source => :topic
    end