2012-03-21 229 views
0

我有一個對象數組,我需要根據子對象average_score屬性對它們進行排序。我試着sort!但這似乎並沒有工作,我不知道我可以在這裏使用Rails的協會:按子對象排序對象數組

collection.sort! do |a, b| 
    a.children.where(:user_id => current_user.id).first.average_score <=> b.children.where(:user_id => current_user.id).first.average_score 
end 

任何人都可以建議我如何才能做到這一點?

+0

你期望的結果是什麼結果呢?或者你得到一個錯誤? – 2012-03-21 20:49:11

+0

你應該使用sort_by,但Ruby會慢得多,SQL ... – tokland 2012-03-21 20:49:54

+0

我希望它根據孩子的average_score排序集合。我得到的錯誤是'nil:NilClass'的未定義方法'average_score'。我認爲這是因爲集合中的一些對象沒有孩子,所以我試圖允許零結果,但零成功 – DanS 2012-03-21 20:51:59

回答

1
collection.sort_by do |x| 
    x.children.where(:user_id => current_user.id).first.average_score 
end 

雖然我會尋找一個純粹和更快的SQL解決方案。

1

當a,b是用戶的情況下,我會做這個

class User 
    has_many :children 

    # This still looks smelly, has many children 
    # but only getting score of first one? 
    def children_average_score 
    first_child = self.children.where(:user_id => self.id).first 

    return first_child.nil ? 0 : first_child.average_score 
    end 
end 

然後您的排序:

collection.sort! do |a, b| 
    a.children_average_score <=> b.children_average_score 
end 
+0

實際上a和b不是User的實例,這些孩子屬於User和另一個模型。該協會在兩個模型的範圍內是一對一的。 – DanS 2012-03-21 21:07:13

+0

你的方法仍然適用,我只需要通過current_user。 – DanS 2012-03-21 21:11:11