leonel
leonel

Reputation: 10224

Rails 3. sort by associated model

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 course

courses
id | name
 1 | biology
 2 | history
 3 | chemistry
 4 | literature

scheduled_courses
id | course_id 
 1 | 2
 2 | 4
 3 | 1
 4 | 2

How can I make an ActiveRecord query to sort the scheduled courses alphabetically?

Upvotes: 11

Views: 5905

Answers (2)

Ben Kreeger
Ben Kreeger

Reputation: 6344

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')

Upvotes: 20

Fellow Stranger
Fellow Stranger

Reputation: 34103

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

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

Upvotes: 13

Related Questions