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

 ̄綄美尐妖づ 提交于 2019-12-04 07:24:42

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.

There are also dynamic finders

Store.find_by_some_id(some_id)

They are equivalent to

Store.where(:some_id => some_id).first

Where clause in rails 3.x will always return and arel objec, which you can use for method chaining.

Thus return statement of the where clause is always an array.

For accessing the first element you have to do

object.first as suggested by Jakub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!