简体   繁体   中英

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.

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.

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)

What you are probably actually looking for is

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM