Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 根据关联记录的比较排序查询_Sql_Ruby On Rails_Ruby_Postgresql_Activerecord - Fatal编程技术网

Sql 根据关联记录的比较排序查询

Sql 根据关联记录的比较排序查询,sql,ruby-on-rails,ruby,postgresql,activerecord,Sql,Ruby On Rails,Ruby,Postgresql,Activerecord,我要从DB中找到男人,我要他们根据长子的年龄来订购。这里有一个例子 class Man has_many :sons # id end class Son belongs_to :man # id, man_id, age end 如何让ActiveRecord执行此操作 编辑 当我尝试执行Man.joins(:sons.order(“sons.age DESC”).uniq时,我得到了无效的SQL first_man = Man.create first_man.son

我要从DB中找到男人,我要他们根据长子的年龄来订购。这里有一个例子

class Man
  has_many :sons

  # id
end

class Son
  belongs_to :man

  # id, man_id, age
end
如何让ActiveRecord执行此操作

编辑

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

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::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
试试这个

 Man.includes(:sons).order("sons.age").to_a
已更新

也许这会有帮助,但这很难看

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

@拉法:你指的是什么?对不起,我当时才意识到,他是第一个。因此,我删除了我的答案。
Son.order('age DESC').map(&:man).uniq