Help with find

Folks   When im in 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, 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 #<ActiveRecord::Relation:0x000000055f8840>

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.

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

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

or

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

and then use the object like this:

p.last_name

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 (https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation.rb#L19) which is located in https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/finder_methods.rb you can do:

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

Hope that helps.