Help with find

7 views
Skip to first unread message

brent brent

unread,
May 18, 2012, 9:01:53 PM5/18/12
to rubyonra...@googlegroups.com
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.

--
Posted via http://www.ruby-forum.com/.

Fernando Almeida

unread,
May 18, 2012, 10:06:15 PM5/18/12
to rubyonra...@googlegroups.com
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 <li...@ruby-forum.com>
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.




--
Fernando Almeida
www.fernandoalmeida.net

Rafael Magaña

unread,
May 19, 2012, 4:51:35 AM5/19/12
to rubyonra...@googlegroups.com
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


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

Hope that helps. 
Reply all
Reply to author
Forward
0 new messages