Rails: Find all with conditions
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?
Solution 1:
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
@fromcanada = User.where(:country => 'canada')
Solution 2:
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.
And for those using Rails 4, removing the all
method will suffice.
@fromcanada = User.where(country: 'canada').to_a
Note that the to_a
calls the query into an array format.