ActiveRecord rails found in console

When I'm in the Rails 3.2 console, I can do it just fine:

p = Person.last
p.last_name

and he prints the last name.

But when I try to find it using id, it can find a single record and save it in my variable p, but I can not print the last_name column. For instance:

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

the print phere shows all the columns but p.last_namesays so

NoMethodError: undefined method `last_name' for
#<ActiveRecord::Relation:0x000000055f8840>

Any help would be appreciated.

+5
source share
4 answers
Inquiry

A wherereturns ActiveRecord::Relationwhich refers to the array, even if you limit the number of records returned.

If you instead change your request to:

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

, , isl , , limit(1).

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

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

, .

EDIT: ActiveRecord:: Relation, @mu , .

+10

:

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

id = 34, 1.

:

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

, :

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

:

p = Person.find(34)
+3

, , , ,

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

Person ApplicationRecord

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

, .

,

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

, p.last_name p.first_name p.

0

All Articles