Ruby-on-rails 如何使用“ActiveRecord::QueryMethods”中的“where”方法来限制搜索?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5267950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use the 'where' method from 'ActiveRecord::QueryMethods' in order to limit searching?
提问by user502052
I am using Ruby on Rails 3 and I would like to limit a search in a wheremethod from ActiveRecord::QueryMethodsusing something as the following
我正在使用 Ruby on Rails 3,我想限制在where方法中的搜索ActiveRecord::QueryMethods使用以下内容
Users.where(:name => "Test_name", :limit => 10)
Users.where(:name => "Test_name").limit(10)
That is, I would like to query only 10 records. How I can do that?
也就是说,我只想查询 10 条记录。我怎么能做到这一点?
In the RoR source code there is:
在 RoR 源代码中有:
def where(opts, *rest)
relation = clone
relation.where_values += build_where(opts, rest) unless opts.blank?
relation
end
回答by Jeremy Ruten
Your second example works:
你的第二个例子有效:
Users.where(:name => "Test_name").limit(10)
There is a nice list and explanation of all the query methods in this Rails guide: http://guides.rubyonrails.org/active_record_querying.html
在这个 Rails 指南中有一个很好的列表和所有查询方法的解释:http: //guides.rubyonrails.org/active_record_querying.html
回答by Shanison
I don't think you can do that in where. You can only do
我不认为你可以在什么地方这样做。你只能做
Users.where(:name => "Test_name").limit(10)
or if you insist to use :limit in other selector method:
或者如果您坚持在其他选择器方法中使用 :limit :
Users.find(:all, :conditions => ["name = 'Test_name'"], :limit => 10)

