【发布时间】:2011-12-24 01:15:35
【问题描述】:
我正在构建一个 twitter 克隆并构建时间线,我需要获取当前用户关注的任何人发布的所有微博。
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 关联?
此外,对于此任务,哪种方法通常更快 - 子选择或连接?
【问题讨论】:
-
你格式化 SQL 的方式伤了我的眼睛。
标签: sql ruby-on-rails activerecord join