我需要獲取所有current_user.friends狀態,然後通過created_at對它們進行排序。Rails:狀態與狀態比較失敗
class User < ActiveRecord::Base
has_many :statuses
end
class Status < ActiveRecord::Base
belongs_to :user
end
而在所述控制器:
def index
@statuses = []
current_user.friends.map{ |friend| friend.statuses.each { |status| @statuses << status } }
current_user.statuses.each { |status| @statuses << status }
@statuses.sort! { |a,b| b.created_at <=> a.created_at }
end
current_user.friends
返回對象的數組User
friend.statuses
返回對象的數組Status
錯誤:
comparison of Status with Status failed
app/controllers/welcome_controller.rb:10:in `sort!'
app/controllers/welcome_controller.rb:10:in `index'
不是你的核心問題,但行走所有這些關聯將通過大量的查詢來殺死你。抓住所有朋友和他們的所有狀態,然後用代碼對它們進行排序可能會產生不合要求的查詢數量,您的性能會迅速下降。爲什麼不寫一個可以一次獲取並排序所有記錄的單個SQL查詢? –
謝謝,我發現了一個簡單的方法和有效的方法:'Status.where(user_id:current_user.friends.map(&:id).insert(0,current_user.id))。all'你怎麼看? – Alex