Rails 3. sort by associated model

后端 未结 2 1039
醉话见心
醉话见心 2021-02-14 02:40

Let\'s say I have two models: Course and ScheduledCourse.

The Course model has a name attribute.

course has_many :scheduled courses scheduled_courses :belongs_to

2条回答
  •  臣服心动
    2021-02-14 03:33

    Try...

    ScheduledCourse.joins(:course).order('course.name')
    

    If this doesn't work, you may need to call .all before your joins condition, like so:

    ScheduledCourse.all.joins(:course).order('course.name')
    

    Like luacassus said, this answer can help; I think the syntax in that answer is pre-Arel (ActiveRecord 3), but it'll get the job done. Hope that helps!

    EDIT:

    As mentioned by @FellowStranger, the correct syntax nowadays seems to be

    ScheduledCourse.joins(:course).order('courses.name')
    

提交回复
热议问题