新手问题 ActiveRecord 如何根据 association 排序

xmonkeycn · 2012年11月06日 · 最后由 xmonkeycn 回复于 2012年11月06日 · 3015 次阅读

有 Student,Exam,Result 三个类,学生会考 0-n 门考试,得到 0-n 个成绩

Student

class Student < ActiveRecord::Base
   has_many :exams, :through => :results
   has_many :results

Exam

class Exam < ActiveRecord::Base
   attr_accessible name
   has_many :students, :through => :results
   has_many :results

Result

class Result < ActiveRecord::Base
   attr_accessible score
   belongs_to :student
   belongs_to :exam

比如我想对学生按照 ruby 的考试成绩排序,可以这么写:

Student.includes(:results).where('results.exam_id ='+Exam.find_by_name('ruby').id.to_s).order('results.score DESC')

(中间的 where 写的很丑,有没有更好的写法?)

但是这样只会得到参加过 ruby 考试的学生的列表,没有 ruby 成绩的学生不会返回。 如何获得包含所有学生的列表,按照 ruby 成绩排序,并且把没有 ruby 成绩的同学排在最后面呢?

谢谢。

ruby_exam = Exam.find_by_name('ruby')
ruby_exam.results.includes(:user).order('results.score DESC')

#1 楼 @fresh_fish

谢谢,这样写好看多了。

我试了一下,这样返回的是 ruby 成绩列表,而不是学生列表。 没有 ruby 成绩学生还是不在列表中。

ruby_exam.results.includes(:user).order('results.score DESC').collect{ |result| result.user }

class Customer < ActiveRecord::Base has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100 end

Student.includes(:results).where('results.exam_id =?',Exam.find_by_name('ruby').id).order('results.score DESC')

#3 楼 @fresh_fish #5 楼 @woaigithub 谢谢,这两个结果还是只有参加过 ruby 考试的 student,没参加过的就木有了-,-

是不是应该对 students 直接 sort_by 呢?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号