在rails3.1中查询

时间:2011-08-30 13:36:17

标签: ruby-on-rails-3 ruby-on-rails-3.1

我在rails3.1的rails控制台中遇到了一个问题

a=User.find_by_name 'castiel'
a.name #output: castiel

a=User.where "name like 'c%'"
a.name #output: User
#both query got the same thing,but why the second one output 'User'

我在rails3.1中使用了一个关于身份验证的新功能,你知道在railscast剧集authentication-in-rails3.1中引入的那个,也许它与此有关,只是觉得让你好知道这里的情况。

2 个答案:

答案 0 :(得分:2)

问题是find_by_namewhere 返回相同的内容。 find_by_name会找到与您的查询匹配的第一个用户。 where将返回与您的查询匹配的用户集合。

在第一个示例中,结果是一个User对象,因此a.name会为您提供"castiel"

a=User.find_by_name 'castiel'
# 'a' will be something like #<User id:..., name: "castiel"...>
a.name #output: castiel

但是,在第二个示例中,结果实际上是一个User对象数组。如果您致电a.name,它将返回其所持模型的名称:User

a=User.where "name like 'c%'"
# 'a' might be something like [#<User id:..., name: "castiel"...>] 
a.name #output: User

即使使用where可能只返回一个结果,它仍然包含在数组中。

答案 1 :(得分:1)

那是因为当你使用where时,它将返回一个ActiveRecord::Relation对象,而不是一个User对象。 find_by_<blahblah>方法返回Model的一个实例。