Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 384
yiinewbie Avatar asked Jan 16 '23 21:01

yiinewbie


1 Answers

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)

like image 109
rcrogers Avatar answered Jan 29 '23 12:01

rcrogers