Help with find

When im in rails 3.2 console i can do this just fine

p = Person.last

and it prints the last name.

But when i try to find it by the id, its able to locate the single
record and store it in my variable p, but i cant print the last_name
column. For example.

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

“printing p here shows all the columns”

p.last_name says this

NoMethodError: undefined method `last_name’ for

any help would be appreciated, thanks.

Person.where.limit returns a collection, you can to use .first, .last,
.each. etc to access the element(s) or you can to use Person.find(34) in
this case.

2012/5/18 brent brent [email protected]

column. For example.

[email protected].
For more options, visit this group at

Fernando A.

There’s no reason to use ‘where’ when you want to select by id since
of the times id is an unique value, and there’s no reason to use
if every time you select by id (SELECT * FROM users where id=34) it
only one row, so you can use:

p = People.find_by_id 34 # this will return nil if id doesn’t exits


p = People.find 34 # this will raise an exception if the id doesn’t

and then use the object like this:


Otherwise, as Fernando pointed out, you’ll get a collection (a kind of
Array) whose type is ActiveRecord::Relation.

If you’re using the console you should realize that when you type "p =
Person.where(id: 34).limit(1) " it returns something like:

[#<Person id: 34, last_name: “the_last_name”…>]

So you should treat it as an Array (actually as an Enumerable) that
responds to :first, :last, :each, etc

Since ActiveRecord::Relation includes the FinderMethods module (
rails/activerecord/lib/active_record/relation.rb at main · rails/rails · GitHub)
which is located in
can do:

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

p = people.find 34

Hope that helps.