开发者

Error when trying to use the new Active Record Query Interface in Rails 3

开发者 https://www.devze.com 2023-01-25 22:14 出处:网络
I\'m trying to use the new Active Record Query Interface for Rails 3. My old style query is my_notes = Note.find(:all, :conditions => { :user_id => current_user.id, :date => p[:date] }, :o

I'm trying to use the new Active Record Query Interface for Rails 3.

My old style query is

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

In the new style, I thought it would be:

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

but I'm getting this error:

NoMethodError in NotesController#play
undefined method `order' for #<A开发者_如何转开发rray:0x00000103d23c38>

What am I doing wrong? Thanks for reading.


find_all_by_<attritubte> is not part of the new ARel syntax. It executes the query immediately and returns an Array with the results. Because the query has already been executed, you can't add any more options, like order to it.

Try this instead:

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


The new query interface works slightly differently - find_all_by_user_id_and_date will return an array of results, whereas order returns an ActiveRecord::Relation object that can then be further scoped.

A working query would be

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

but it would generally be better to use the AREL syntax for your query:

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

精彩评论

暂无评论...
验证码 换一张
取 消