Rails的3排序相关的型号 [英] Rails 3. sort by associated model
问题描述
让我们说我有两个型号:课程和ScheduledCourse
Let's say I have two models: Course and ScheduledCourse.
该课程模式有一个name属性。
The Course model has a name attribute.
当然的has_many:预定课程 scheduled_courses:belongs_to的课程
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
我怎样才能让一个ActiveRecord查询到预定的课程按字母顺序排序?
How can I make an ActiveRecord query to sort the scheduled courses alphabetically?
推荐答案
试试...
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')
喜欢的 luacassus 的说,<一个href="http://stackoverflow.com/questions/1530131/rails-order-using-a-has-many-belongs-to-relationship">this的回答可以帮助;我认为这个问题的答案语法是pre-阿雷尔(ActiveRecord的3),但它会完成这项工作。希望帮助!
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!
编辑:
正如刚才@FellowStranger,正确的语法时下似乎
As mentioned by @FellowStranger, the correct syntax nowadays seems to be
ScheduledCourse.joins(:course).order('courses.name')
这篇关于Rails的3排序相关的型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!