按子属性对对象数组进行排序

时间:2012-03-21 20:42:27

标签: ruby-on-rails ruby arrays sorting

我有一个对象数组,我需要根据孩子的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

有人可以建议我怎么做吗?

2 个答案:

答案 0 :(得分:1)

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

虽然我会寻找一种更纯粹,更快速的SQL解决方案。

答案 1 :(得分:1)

当a,b是User的实例时,我会这样做

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