Rails3 中 select 的奇怪之处
在我的应用程序中,我有这条线
Feature.all(:select=>"name", :conditions=> ['id IN (?)', feature_id_array]).map(&:name)
并且工作正常。
当我将它重新编写为 Rails3 语法时,
Feature.find(feature_id_array).select('name').map(&:name)
它向我抛出一个错误,说“
ArgumentError in AuthoringController#edit
wrong number of arguments(1 for 0)
app/models/widgets/widget_feature.rb:82:in `select'
所以,我在控制台做了一些随机查询,发现:
Model.find(id_array).select(attribute)
返回相同的错误,而
Model.select(attribute).find(id_array)
工作正常”。
有人可以告诉我这是为什么吗?我一直在摸不着头脑,但没有找到正确的原因:
Model.select(attribute) 将首先获取所有记录并选择它们的名称,然后它将在 id_array 中找到具有匹配 id 的记录。< /strong>
如果我只想要 10 个记录的名称,那么上面的查询将首先从表中检索所有记录的名称,然后获取所需的 10 个名称。
编辑: 注意:以下查询工作正常:
Model.where(:id => id_array).select(attribute)
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 required 10 names.
Edited:
NOTE : The following query works fine:
Model.where(:id => id_array).select(attribute)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Jatin,
“find”方法不会像 where 或 select 那样返回 ActiveRelation。由于它返回 ActiveRecord::Base 对象或数组,因此您无法在其上添加 ActiveRelation 子句。您的替代方案有效,因为“where”也在早期关系中返回 ActiveRelation (Model.where()),可以在 ActiveRelation 上调用 find (Model.select().find() - 有效)。
因此,请使用 ActiveRelations 或使用 find,但混合两者时要小心。如果混合两者,请确保 find 出现在最后。
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.
尝试一下
这有助于解释查询与 Rails2 的不同之处:http://m.onkey。 org/active-record-query-interface
Try
This is helpful in explaining how querying is different from Rails2: http://m.onkey.org/active-record-query-interface