I got an issue in rails3.1, in the rails console
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'
I used a new feature in rails3.1 which is about authentication, you know the one that introduced in railscast episode authentication-in-rails3.1,maybe it's got something to do with this,just thought it might be good to let u know the开发者_JAVA百科 circumstances here.
The issue is that find_by_name
and where
are not returning the same thing. find_by_name
will find the first User that matches your query. where
will return a collection of Users that match your query.
In your first example, the result is a single User object, so a.name
gives you "castiel"
.
a=User.find_by_name 'castiel'
# 'a' will be something like #<User id:..., name: "castiel"...>
a.name #output: castiel
In the second example, however, the result is essentially an array of User objects. If you call a.name
, it will return the name of the model it holds: User
.
a=User.where "name like 'c%'"
# 'a' might be something like [#<User id:..., name: "castiel"...>]
a.name #output: User
Even though using where
probably only returns you one result, it's still wrapped in an array.
That's because when you use where
it will return a ActiveRecord::Relation
object and not a User object. find_by_<blahblah>
method returns an instance of the Model.
精彩评论