2013-07-03 48 views
1

我有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上?换句话说,我怎样才能将这两个查询合并为一个?

感谢

+0

我写了一个SQL来实现这一目标。 –

回答

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 
+0

你好,谢谢你的努力,我正在尝试这个,但无法克服这个错误信息:'SQLite3 :: SQLException:模棱两可的列名:id:SELECT id FROM“users”INNER JOIN“friendships”ON“users” id“=”友谊“。”friend_id“在哪里”友谊“。”user_id“= 2和”友谊“。”证实“='t'' - 怎么了? – user984621

+0

'current_user.friends'返回一个用户当前的朋友数组,对吗?它应该是因为你有'用户有很多朋友'的关系。 – rmagnum2002

+0

你可以这样试试'ids = current_user.friends.map {| f | f.id} << current_user.id',它会返回一个包含你自己的id数组,看它是否有效。可能是采摘方法不适合你。 – rmagnum2002

相关问题