获取当前用户所发布的所有微博客
问题描述:
我正在构建微博克隆并构建时间表,我需要获取当前用户关注的任何人发布的所有微博客。获取当前用户所发布的所有微博客
Railstutorial.org implements it like this:
class Micropost < ActiveRecord::Base
default_scope :order => 'microposts.created_at DESC'
# Return microposts from the users being followed by the given user.
scope :from_users_followed_by, lambda { |user| followed_by(user) }
private
# Return an SQL condition for users followed by the given user.
# We include the user's own id as well.
def self.followed_by(user)
following_ids = %(SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where("user_id IN (#{following_ids}) OR user_id = :user_id",
{ :user_id => user })
end
end
但我觉得自己像一个子选择是有点乱,我想我更喜欢通过加入做到这一点。这里是我想要的SQL:
SELECT m.*
FROM Users u
INNER JOIN Follows f
ON u.id = f.follower_id
INNER JOIN Microposts m
ON s.user_id = f.followee_id
WHERE u.id = [current users id]
ORDER BY m.posted_at DESC
如何将这个转换为ActiveRecord关联?
此外,哪种方法通常对于此任务会更快 - 子选择还是连接?
答
试试这个:
class User
has_many :posts
has_many :follower_links, :class_name => "Follow", :foreign_key => :followee_id
has_many :followers, :through => :follower_links, :source => follower
has_many :followee_links, :class_name => "Follow", :foreign_key => :follower_id
has_many :followees, :through => :followee_links, :source => followee
def followee_posts
Post.joins("JOIN (#{followees.to_sql}) AS followees
ON posts.user_id = followees.id")
end
end
class Follow
belongs_to :followee, :class_name => "User"
belongs_to :follower, :class_name => "User"
end
class Post
belongs_to :user
end
格式化SQL的方式伤害了我的眼睛。 – 2011-12-24 01:18:31