1

I have 2 models, user and friendship, here's how they looks like:

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

and

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

and here's how I fetch posts of currently logged in user and posts of his/her friends:

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

This is working well, but how can I load my posts + posts of my friends into one variable and display them as on Facebook? In other words, how can I merge those 2 queries into only one?

Thanks

4

1 回答 1

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
于 2013-07-03T12:00:04.483 回答