问题
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