Model.all中的Where子句

时间:2012-08-18 17:07:20

标签: ruby-on-rails ruby

我是ruby的新手并拥有以下内容:

students = Student.all(:order => "score DESC",
            :limit => 5)

但是我想在其中放入一个where子句,但是我收到错误“Unknown key:where”。我的student表引用了exam表(t.references :exam),其中包含date字段,因此我需要执行以下操作:

students = Student.all(:where => "exam.date='01/01/2012'",
                       :order => "score DESC",
                       :limit => 5)

如何在where方法中使用all子句且exam.date='01/01/2012'是否正确?

2 个答案:

答案 0 :(得分:5)

带有参数的all方法是一个pre-Rails 3 API,而all(*args)相当于find(:all, *args),它采用:conditions选项:

students = Student.all(:conditions => "exam.date='01/01/2012'",
                       :order => "score DESC",
                       :limit => 5)

通常首选使用Rails 3的可链式关系方法:

students = Student.where("exam.date='01/01/2012'").order('score DESC').limit(5)

答案 1 :(得分:1)

您应该使用#where方法:

students = Students.where('exam.date = ?', '01/01/2012').all(order: 'score DESC', limit: 5)