开发者

Weird thing with select in Rails3

开发者 https://www.devze.com 2023-02-04 09:36 出处:网络
In my app, I have the line Feature.all(:select=>\"name\", :conditions=> [\'id IN (?)\', feature_id_array]).map(&:name)

In my app, I have the line

Feature.all(:select=>"name", :conditions=> ['id IN (?)', feature_id_array]).map(&:name)

and it works fine.

When i re-wrote it to the Rails3 syntax,

Feature.find(feature_id_array).select('name').map(&:name)

it throws me an error, saying

ArgumentError in AuthoringController#edit

   wrong number of arguments(1 for 0)

app/models/widgets/widget_feature.rb:82:in `select'

So, I did some random queries at console and found that:

Model.find(id_array).select(attribute)

returns the same error, while

Model.select(attribute).find(id_array)

works fine.

Could someone tell me the reason for this. I have been scratching my head but didnt get to a proper reason as :

Model.select(attribute) will first fetch all the records and select their names, and then it will find the records with the matching ids in id_array.

If i want names of just 10 records, then the above query will first retrieve names of all the records from the table and then get me the requ开发者_如何学Pythonired 10 names.


Edited: NOTE : The following query works fine:

Model.where(:id => id_array).select(attribute)


Jatin,

The method "find" does not return an ActiveRelation like where or select does. Since it returns an ActiveRecord::Base object or an Array you cannnot add ActiveRelation clauses on that. Your alternatives work because "where" returns an ActiveRelation (Model.where()) also in the earlier relation, find can be called on an ActiveRelation (Model.select().find() - works).

So use ActiveRelations or use find but be careful when mixing both. If you mix both, ensure find comes at the end.


Try

Feature.find(feature_id_array, :select => :name).map(&:name)

This is helpful in explaining how querying is different from Rails2: http://m.onkey.org/active-record-query-interface

0

精彩评论

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