在Rails 3活动记录查询中使用WHERE子句

yii*_*bie 4 ruby activerecord ruby-on-rails

我是rails的新手,我正在尝试使用where方法从我的数据表中检索记录.但是,使用它似乎不会返回任何结果.

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
Run Code Online (Sandbox Code Playgroud)

我正在通过打印测试结果employee.first_name,就像我说前两个不返回任何东西而第三个返回"bill".这里发生了什么?

rcr*_*ers 8

前两个将返回一个数组(所有具有该名称的员工). Employee.find_by_first_name只会返回第一个结果 - Employee.find_all_by_first_name应该像前两个查询一样返回一个数组.

看看这是否符合您的期望:

Employee.where("first_name = ?", "bill").first
Run Code Online (Sandbox Code Playgroud)

(为了完整性,有什么Employee.where实际返回的是一个环连接的范围对象的行为等的阵列)