0
我正嘗試爲用戶構建一個Facebook樣式的項目源。 Feed中會包含用戶或用戶關注的其他通知(例如「您關注的用戶x開始閱讀新書」)的用戶所做的最新筆記(書籍)。你明白了。在rails中結合作用域活動記錄查詢
到目前爲止,我有我的筆記類範圍返回我想說明:
class Note < ActiveRecord::Base
scope :from_users_followed_by, lambda { |user| followed_by user }
def self.followed_by(user)
followed_ids = %(SELECT followed_id FROM relationships WHERE follower_id = :user_id)
where("user_id IN (#{followed_ids}) OR user_id = :user_id", { :user_id => user })
end
end
,並在我的閱讀類的類似範圍返回內置記錄時,用戶開始讀一本書:
class Reading < ActiveRecord::Base
scope :from_users_followed_by, lambda { |user| followed_by(user) }
def self.followed_by(user)
# is this not at risk of sql injection??
followed_ids = %(SELECT followed_id FROM relationships WHERE follower_id = :user_id)
# return readings where user_id IN (an array of user_ids that the user follows)
where("reader_id IN (#{followed_ids}) OR reader_id = :user_id", { :user_id => user })
end
end
現在,這工作正常,我可以從這些沒有問題的對象的數組。我正努力將這兩個查詢合併到一個按創建時間正確排序的提要中。我當時可以做的最好的是我的用戶類組合進料方法:
class User < ActiveRecord::Base
def combined_feed
feed = Note.from_users_followed_by(self) | Reading.from_users_followed_by(self)
feed.sort! do |a, b|
a.created_at <=> b.created_at
end
feed.reverse
end
end
它得到了我的組合進料,但給我的印象爲窘況效率低下。我如何在rails中的數據庫級別執行相同的操作?