Rails: Find all with conditions

Ruby on-Rails

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeahcimView Question on Stackoverflow
Solution 1 - Ruby on-RailsWaynn LueView Answer on Stackoverflow
Solution 2 - Ruby on-Railsthank_youView Answer on Stackoverflow