Question

I have a model of users and things

Users can have one leader and many followers which are other users. User can also have things

So I have these definitions which use a self join relationship:

class User < ActiveRecord::Base
    has_many :things, dependent: :destroy
    has_many :followers, :class_name => 'User', :foreign_key => 'leader_id'
    belongs_to :leader, :class_name => 'User', :foreign_key => 'leader_id'
end

class Thing < ActiveRecord::Base
    belongs_to :user
end

So I can query ask for a list of things that a user has by asking, for example User.first.things. I can also get a list of followers of a user with User.first.followers.

How do I get a list of things that a user's followers have. I think I might need to use a has_many through relationship but I can't seem to figure it out as I'm not sure how to deal with the fact that a Leader can have things through a 'follower' but also directly themselves

Thanks

Was it helpful?

Solution

Something like this:

def all_things
  Thing.where(:user_id => followers.map(&:id).push(id))
end

It returns a scope so you should be able to continue the chain, for example:

User.first.all_things.visible

Update

If you are only interested in the followers' things without adding the user's things to the batch it is better is you do it directly with a has_many through:

has_many :followers_things, :through => :followers, :source => :things

Check this other SO thread

OTHER TIPS

How about:

all_things = (your_user.followers.each { |f| f.things }).flatten

This should return an array containing things that belong to all your_user's followers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top