2

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

2 Answers2

0

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.

Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
0

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

Community
  • 1
  • 1
fguillen
  • 36,125
  • 23
  • 149
  • 210
  • Just beware this solution is not following an infinite recursion among all the levels of `leadership`. Meaning that this solution is not having in consideration that a `follower` can also be a `leader` for other `users` and so also having inherited `things`. – fguillen Nov 21 '13 at 23:43
  • This is on the right track. At the moment it returns (as the name suggests) all the things which a `user` has and which their `followers` have. I just want things their `followers` have. But I should be able to figure it from here – user3019256 Nov 22 '13 at 00:05
  • Got it, just drop the `.push(id)` so: `Thing.where(:user_id => followers.map(&:id))' worked for what I needed – user3019256 Nov 22 '13 at 00:22
  • I was confused by the part of your description that says: _a Leader can have things through a 'follower' but also directly themselves_ – fguillen Nov 22 '13 at 09:27