Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 871
Leahcim Avatar asked Mar 10 '12 21:03

Leahcim


People also ask

What is ActiveRecord in Ruby on Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is ORM in Ruby on Rails?

Object Relational Mapping (ORM) is the technique of accessing a relational database using an object-oriented programming language. Object Relational Mapping is a way for our Ruby programs to manage database data by "mapping" database tables to classes and instances of classes to rows in those tables.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.


1 Answers

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') 
like image 184
Waynn Lue Avatar answered Sep 28 '22 08:09

Waynn Lue