我有两个模型,用户和友谊,下面是它们的样子:
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上显示出来呢换句话说,如何将这两个查询合并为一个查询?
谢谢
最佳答案
像这样的:
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