Ruby on rails 按父属性对子模型进行排序具有一个关联

Ruby on rails 按父属性对子模型进行排序具有一个关联,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,我想按父母的名字给孩子下单 class Child < ApplicationRecord belongs_to :parent, -> { order(:name) } end class Parent < ApplicationRecord default_scope { order(:name) } has_one :child end 不会返回正确的结果。 有什么好办法吗 Child.includes(:parent).order("parents.n

我想按父母的名字给孩子下单

class Child < ApplicationRecord
  belongs_to :parent, -> { order(:name) }
end

class Parent < ApplicationRecord
  default_scope { order(:name) }

  has_one :child
end
不会返回正确的结果。 有什么好办法吗

Child.includes(:parent).order("parents.name desc").as_json(include: { parent: { only: :name } })

这对我很有用。

你能不能做到:
@children=Child.all.includes(:parent.order(“parent.name desc”)
@ruby\u newbie我不知道你的意思。我编辑了其他评论。最终,我将在返回此查询的名为“by\u parent”的子级上定义一个作用域。@ruby\u newbie,您能共享该作用域吗?Child.all.includes(:parent.order)(“parent.name desc”)不正确,因为父表不存在。另外,不需要all。因此Child.includes(:parent.order(“parents.name desc”)是正确的。谢谢!
Child.includes(:parent).order("parents.name desc").as_json(include: { parent: { only: :name } })