根据相关记录的比较订购查询

时间:2014-03-23 02:36:03

标签: sql ruby-on-rails ruby postgresql activerecord

class Man
  has_many :sons

  # id
end

class Son
  belongs_to :man

  # id, man_id, age
end

我是从DB中检索男人,我希望他们根据他们大儿子的年龄来订购。这是一个例子。

first_man = Man.create
first_man.sons.create(age: 10)
first_man.sons.create(age: 5)

second_man = Man.create
second_man.sons.create(age: 20)
second_man.sons.create(age: 5)

third_man = Man.create
third_man.sons.create(age: 19)
third_man.sons.create(age: 8)

Man.order('[some order]').to_a
=> [second_man, third_man, first_man]

如何让ActiveRecord执行此操作?

修改

当我尝试Man.joins(:sons).order("sons.age DESC").uniq时,我得到了无效的SQL。

ActiveRecord::StatementInvalid:
       PG::InvalidColumnReference: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
       LINE 1: ...sons"."man_id" = "men"."id"  ORDER BY sons...
                                                                    ^
       : SELECT  DISTINCT "men".* FROM "men" INNER JOIN "sons" ON "sons"."man_id" = "men"."id"  ORDER BY sons.age DESC LIMIT 15

2 个答案:

答案 0 :(得分:0)

没试过,但我想这应该有用

 Man.includes(:sons).order("sons.age").to_a

答案 1 :(得分:0)

试试这个

Man.joins(:sons).order('sons.age DESC').uniq

<强>更新

也许这会有所帮助但是很难看

Son.order('age DESC').map(&:man).uniq