0
我正在構建微博克隆並構建時間表,我需要獲取當前用戶關注的任何人發佈的所有微博客。獲取當前用戶所發佈的所有微博客
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的方式傷害了我的眼睛。 – 2011-12-24 01:18:31