2011-08-30 36 views
0

我在rails3.1一个问题,在轨控制台查询在rails3.1

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

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

在第一个示例中,结果是一个用户对象,因此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可能只返回一个你的结果,它仍然包裹在一个阵列。

+0

啊!谢谢你,我犯了一个多么愚蠢的错误 – castiel

1

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

+0

谢谢你们,男人 – castiel