【发布时间】:2013-07-03 11:55:55
【问题描述】:
我有 2 个模型,user 和 friendship,它们的外观如下:
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 上一样显示它们?换句话说,我怎样才能将这 2 个查询合并为一个?
谢谢
【问题讨论】:
-
我写了一个 SQL 来实现。
标签: ruby-on-rails ruby activerecord model associations