user740970
user740970

Reputation: 269

rails ActiveRecord find in console

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.

Upvotes: 8

Views: 36873

Answers (4)

Sai Ram Reddy
Sai Ram Reddy

Reputation: 1089

In your case Person is a class and it is inherited from ApplicationRecord

p = Person.where(id:10).limit(1)

It returns just the result of the query not the object.

You can check it by using

p.class # => It reurns Nilclass which means its not at all a class 

So you cannot use p.last_name or p.first_name on p.

Upvotes: 0

Kevin Bedell
Kevin Bedell

Reputation: 13404

This returns a collection of active record objects:

p = Person.where(id: 34).limit(1)

But there's only one with id = 34, so it's a collection of 1.

The way to do this is:

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

or, better:

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

or, even better:

p = Person.find(34)

Upvotes: 4

x1a4
x1a4

Reputation: 19475

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.

Upvotes: 16

DVG
DVG

Reputation: 17480

What you are probably actually looking for is

@person = Person.find(34)
@person.last_name

Upvotes: 1

Related Questions