Reputation: 11095
I've implemented "following" function. Showing "people user A is following" was simple, but showing "people who are following user A" is giving me troubles.
I have follow_links, which have id, user_id, and follow_you_id column. When user A begins following user B, the columns will be like (user_id = A, follow_you_id = B).
To show users that A(@user) is following, I can simply do
@follow_yous = @user.follow_yous
But I'm not sure how to show users who are following A(@user)
To do this, I first found all the related links.
@follow_links = FollowLink.where(:follow_you_id => @user.id)
Now I thought I could just do @follow_mes = @follow_links.users
, but it says user
is an undefined method. So I guess I can either call user.follow_yous
or follow_you.users
.
My next approach was
@follow_links = FollowLink.where(:follow_you_id => @user.id)
@follow_mes = User.where(:id => @user.id, :include => @follow_links)
I intended to find all the User objects that had the provided @follow_links objects, but I think the syntax was wrong. I couldn't find a decent solution after a bit of research. I'd appreciate any help.
Update: FollowLink model
belongs_to :user
belongs_to :follow_you, :class_name => "User"
Upvotes: 1
Views: 49
Reputation: 43298
You can use joins
like this:
@users = User.joins(:follow_links).where(:follow_links => { :follow_you_id => @user.id })
Upvotes: 2
Reputation: 11811
you can use following:
@follow_links = FollowLink.where(:follow_you_id => @user.id)
@follow_links.collect(&:user) # :user should be the name of your relation to user in your followlink model
=> [User1, User2,...]
Upvotes: 1