views:

174

answers:

2

I have a twitter style application whereby a user follows many people. This is achieved using a self-referential association.

This all works very nice but my brain has just gone dead while trying to figure out the active record syntax needed to list status updates (posts) from people the user follows ordered by time in a single query.

My user model looks like this

class User < ActiveRecord::Base
    has_many :posts
    has_many :friendships
    has_many :friends, :through => :friendships
end

And the post model is

class Post < ActiveRecord::Base
    belongs_to :user
end

For completeness the Friendship model

class Friendship < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, :class_name => "User"
 end

Ultimately what I want to do is

@user.friends.reviews.all

+1  A: 

I'm assuming that a friend is also a User object, so that Friend also has_many :posts:

@user.friends.posts.find(:all, :order => "created_at DESC"

Eric Hill
Yes, that's correct. friend is a User object and has_many :posts but when I try to use your snippet I getundefined method `posts' for #<Class:0x102efd118>
KJF
You also need User has_many :friends above your :through line.
Eric Hill
Not sure I understand you there.Are you saying I need to have has_many :friends defined twice in the user model?
KJF
+1  A: 

I think your problem is stemming from the fact that @user.friends is returning an array and so .posts doesn't exist on an array (even if it's an array of AR objects).

I would probably define something like User#friend_posts which builds up an array of friends posts that you can return.

Something like:

def friend_posts
  posts = []
  friends.each { |friend| posts << friend.posts }
  posts
end
theIV
The problem I see with that is that the posts are not sorted by the create time. Also, this would involve grabbing every single post from each person the user follows. It just feels like there should be a nicer way of doing this.
KJF