Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a single record lookup return an array? (Rails beginner)

I have a where operation on a model that returns a single object. But I can't seem to use it in object notation (it appears to return an array with the object at [0]).

store = Store.where("some_id = ?", some_id)

puts store.name  # doesn't work

puts store  # shows array with the object at [0]
like image 304
Hopstream Avatar asked Nov 06 '11 09:11

Hopstream


2 Answers

Because sometimes you don't know how many objects a query should return, so for consistency you always get an array.

To get a single object use

store = Store.where("some_id = ?", some_id).first

If you are looking for the primary ID of the model, you can also use

store = Store.find(some_id)

which will raise a RecrodNotFound exception (handled by rails as a 404 by default) if it doesn't find the object.

like image 193
Jakub Hampl Avatar answered Oct 06 '22 01:10

Jakub Hampl


There are also dynamic finders

Store.find_by_some_id(some_id)

They are equivalent to

Store.where(:some_id => some_id).first
like image 43
Simon Perepelitsa Avatar answered Oct 06 '22 02:10

Simon Perepelitsa