2012-03-21 142 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