rails ActiveRecord find in console

activerecord, ruby-on-rails, ruby-on-rails-3

Solution

A `where` query will return an `ActiveRecord::Relation`, which sort of acts like an array, even if you limit the number of returned records.

If you instead change your query to:

p = Person.where(id: 34).first

it will work as you want, and arel knows to automatically limit the query to a single result, so you don't have to explicitly specify `limit(1)`.

You could also change to either

p = Person.find(34) # Throws an ActiveRecord::RecordNotFound exception if Person with id 34 does not exist

or

p = Person.find_by_id(34) # Returns nil if Person with id 34 does not exist. Does *not* throw an exception.

and it will return a single record as expected.

EDIT: A where query returns an ActiveRecord::Relation, as @mu is too short mentioned in comments.

Problem

When I'm in the Rails 3.2 console, I can do this just fine: ``` p = Person.last p.last_name ``` and it prints the last name. But when I try to find it by the `id`, it's able to locate the single record and store it in my variable `p`, but I can't print the `last_name` column. For example: ``` p = Person.where(id: 34).limit(1) ``` printing `p` here shows all the columns but `p.last_name` says this ``` NoMethodError: undefined method `last_name' for #<ActiveRecord::Relation:0x000000055f8840> ``` any help would be appreciated.

Original source