Rails 3. sort by associated model

后端 未结 2 1040
醉话见心
醉话见心 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')
    
    0 讨论(0)
  • 2021-02-14 03:35
    ScheduledCourse.joins(:course).order('courses.name asc')
    

    Note that the table name should be in plural. This code is tested.

    0 讨论(0)
提交回复
热议问题