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?
这很好用,但是如何将我的帖子+朋友的帖子加载到一个变量中并在Facebook上显示它们?换句话说,如何将这两个查询合并为一个?
Thanks
1 个解决方案
#1
3
something like this:
像这样的东西:
ids = current_user.friends.pluck(:id) << current_user.id
posts = Post.where(user_id: ids)
return
SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1, 2, 3, 6)
then in view:
然后在视野中:
posts.each do |post|
....
end
#1
3
something like this:
像这样的东西:
ids = current_user.friends.pluck(:id) << current_user.id
posts = Post.where(user_id: ids)
return
SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1, 2, 3, 6)
then in view:
然后在视野中:
posts.each do |post|
....
end