yiinewbie
yiinewbie

Reputation: 1055

using WHERE clause in Rails 3 active record query

I'm new to rails and I'm trying to use the where method to retrieve a record from my data table. However, using it doesn't seem to return any results.

employee = Employee.where("first_name = ?", "bill")  #doesn't work

employee = Employee.where(:first_name => "bill")  #doesn't work

employee = Employee.find_by_first_name("bill")  #works

I'm testing the results by printing employee.first_name and like I said the first two don't return anything whereas the third one returns "bill". What's going on here?

Upvotes: 4

Views: 10344

Answers (2)

jalvarado
jalvarado

Reputation: 196

what happens for the first two when you run employee.first_name? It looks to me like you should be getting an no method exception since Array does not have a method first_name.

Using the where clause will not automatically return the first employee model object found, it will return an ActiveRecord::Relation which will then be automatically evaluated into an array by rails when you try to access it. The where clause will give you back all employees with a first_name == "bill"

The find_by_first_name will only return a single instance of the Employee class, even if there are multiple employees with the name "bill".

If you were to try employee.first.fist_name after running the first two, I believe you would find that you get "bill" if everything in the database is correct and there is an employee with the first name of "bill".

Upvotes: 1

rcrogers
rcrogers

Reputation: 2331

The first two will return an array (all employees with that name). Employee.find_by_first_name will only return the first result -- Employee.find_all_by_first_name should return an array like the first two queries.

See if this does what you expect:

Employee.where("first_name = ?", "bill").first

(for completeness, what Employee.where actually returns is a chainable scope object that acts like an array)

Upvotes: 8

Related Questions