4

我是 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

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

4

2 回答 2

8

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

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

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

(为了完整起见,实际返回的是一个数组一样的Employee.where可链接范围对象)

于 2012-04-19T16:34:03.167 回答
1

跑步时前两个会发生什么employee.first_name?在我看来,您应该得到一个 no method 异常,因为 Array 没有 method first_name

使用 where 子句不会自动返回找到的第一个员工模型对象,它会返回一个 ActiveRecord::Relation,然后当您尝试访问它时,rails 将自动将其计算为一个数组。where 子句将返回所有具有 first_name == "bill" 的员工

find_by_first_name即使有多个名为“bill”的员工,也只会返回 Employee 类的单个实例。

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".

于 2012-04-19T16:34:54.240 回答