Ruby-on-rails Rails:查找所有条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9650205/
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
Rails: Find all with conditions
提问by Leahcim
in my app I have users from different countries and want to perform finds on them
在我的应用程序中,我有来自不同国家的用户,并希望对他们进行查找
I tried to do it like this in the index action
我试图在索引操作中这样做
@fromcanada = User.find(:all, :country => 'canada')
but I got the error
但我得到了错误
Unknown key: country
However, so that leads me to ask, what can become a key? In my database schema file, I have a "country" column on the users table.
然而,这让我想问,什么可以成为钥匙?在我的数据库架构文件中,我在用户表上有一个“国家”列。
t.string "country"
Furthermore, when I did a find all
此外,当我找到所有
@users = User.all
I was able to do this
我能够做到这一点
<%= user.country %></p>
Can you explain why my find all with conditions didn't work? and show me how I should have done it?
你能解释一下为什么我的 find all with conditions 不起作用吗?告诉我我应该怎么做?
回答by Waynn Lue
Try this.
尝试这个。
@fromcanada = User.find(:all, :conditions => { :country => 'canada' })
edit: As jason328 pointed out, the above answer is deprecated in 3.2, and an updated answer would be
编辑:正如 jason328 所指出的,上述答案在 3.2 中已被弃用,更新的答案将是
@fromcanada = User.where(:country => 'canada')
回答by jason328
In case no one read the comments. A better format would be
万一没人看评论。更好的格式是
@fromcanada = User.where(country: 'canada').all
The previous answer's code is being deprecated in 3.2.
上一个答案的代码在 3.2 中已被弃用。
And for those using Rails 4, removing the allmethod will suffice.
对于那些使用 Rails 4 的人,删除该all方法就足够了。
@fromcanada = User.where(country: 'canada').to_a
Note that the to_acalls the query into an array format.
请注意,将to_a查询调用为数组格式。

