I need to find all comments made by people that a user is following,
which in effect is this simple SQL query:
select comments.title
from comments, followings, users
where users.id = followings.follower_id
and followings.user_id = comments.user_id
and users.id = 1
Can someone help? I tried this but it didn't work:
class User ...
has_many :followings
class Following ...
has_many :comments, :foreign_key => 'user_id'
script/console
User.find(:first).followings (this works)
Following.find(:first).comments (this works)
User.find(:first).followings.comments (this does NOT work)
There's probably a more elegant way to do this (and I'm sure you could
improve on my choice of words for 'admirers' and 'followed' ) but
hopefully it gets you in the right direction.
Thanks Stu. The solution above works but I'm looking for a find
statement that will perform a single db query (like the SQL statement
I posted) versus performing multiple queries and adding them using
ruby. If a user has a hundred followers wouldn't your solution
perform a hundred queries?
Thanks Stu. The solution above works but I'm looking for a find
statement that will perform a single db query (like the SQL statement
I posted) versus performing multiple queries and adding them using
ruby. If a user has a hundred followers wouldn't your solution
perform a hundred queries?
Actually more like 200 :=)
One way is to just use the same joins that your raw sql had, just in a
more activerecordy way eg