Rails order by associated data

佐手、 提交于 2019-12-11 17:34:39

问题


Is it possible to order the results of school.classrooms by the teacher's name? I want to do this directly in the association, and not a separate call.

class School < ActiveRecord::Base
  has_many :classrooms
end


class Classroom < ActiveRecord::Base
  belongs_to :school
  belongs_to :teacher
end


class Teacher < ActiveRecord::Base
  has_one :classroom
end

回答1:


This should work if you are using rails 3.x

school.classrooms.includes(:teacher).order("teachers.name")


来源:https://stackoverflow.com/questions/8875184/rails-order-by-associated-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!