2010-11-18 54 views
1

我试图使用new Active Record Query Interface为Rails 3错误尝试使用新的活动记录查询界面中的Rails 3

我的老样式的查询是

my_notes = Note.find(:all, :conditions => { :user_id => current_user.id, :date => p[:date] }, :order => "date ASC, created_at ASC") 

在新的风格时,我认为这将是:

my_notes = Note.find_all_by_user_id_and_date(current_user.id, p[:date]).order('date ASC, created_at ASC') 

,但我得到这个错误:

NoMethodError in NotesController#play 
undefined method `order' for #<Array:0x00000103d23c38> 

我在做什么错?谢谢阅读。

+1

看来,'find_all'返回数组。也许你可以切换到“哪里”? – 2010-11-18 10:35:06

回答

4

新的查询界面的工作方式略有不同 - find_all_by_user_id_and_date会返回结果的数组,而order返回然后可以进一步作用域一个ActiveRecord :: Relation对象。

一个工作的查询是

my_notes = Note.order('date ASC, created_at ASC').find_all_by_user_id_and_date(current_user.id, p[:date]) 

但它通常会更好地使用AREL语法查询:

my_notes = Note.where(:user_id => current_user.id, :date => p[:date]).order('date ASC, created_at ASC').all 
+0

这就是我说:) – Ariejan 2010-11-18 10:30:38

+0

@Ariejan当时我没有发布我的答案,它不是,我发布后添加额外的信息。 – nobody 2010-11-18 10:32:46

+0

嗯,伟大的思想:) – Ariejan 2010-11-18 11:00:14

6

find_all_by_<attritubte>不是新的ARel语法的一部分。它立即执行查询并返回一个包含结果的数组。由于查询已执行,因此您无法再添加其他选项,例如order

试试这个:

Note.find.where(:user_id => current_user.id, :date => p[:date]).order('date ASC, created_at ASC')