开发者

Ruby on Rails active record syntax to query status updates in a twitter style application

开发者 https://www.devze.com 2022-12-18 19:41 出处:网络
I have a twitter style application whereby a user follows many people. This is achieved using a self-referential association.

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


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"


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号