我在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中引入的那个,也许它与此有关,只是觉得让你好知道这里的情况。
答案 0 :(得分:2)
问题是find_by_name
和where
不返回相同的内容。 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的一个实例。