如何打印我朋友的帖子和帖子?

时间:2013-07-03 11:55:55

标签: ruby-on-rails ruby activerecord model associations

我有2个型号,用户友情,以下是它们的样子:

class User < ActiveRecord::Base
  has_many :posts
  has_many :friendships, :conditions => { :confirmed => true }
  has_many :friend_requests, :class_name => 'Friendship', :conditions => { :confirmed => false }
  has_many :friends, :through => :friendships
  has_many :friends_friendships, :through => :friends, :source => :friendships
  has_many :friends_of_friends, :through => :friends_friendships, :source => :friend
  has_many :friends_listings, :through => :friends, :source => :listings
  has_many :friends_posts, :through => :friends, :source => :posts
  ...
end

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

以下是我如何获取当前登录用户的帖子以及他/她朋友的帖子:

  @my_posts = current_user.posts.includes(:user)
  @friends_posts = current_user.friends_posts.includes(:user)

这很好用,但是如何将我的帖子+朋友的帖子加载到一个变量中并将其显示在Facebook上?换句话说,如何将这两个查询合并为一个?

由于

1 个答案:

答案 0 :(得分:3)

类似的东西:

ids = current_user.friends.pluck(:id) << current_user.id
posts = Post.where(user_id: ids)

返回

SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1, 2, 3, 6)

然后在视图中:

posts.each do |post|
  ....
end