为什么单条记录查找返回一个数组?(Rails 初学者) [英] Why does a single record lookup return an array? (Rails beginner)

查看:35
本文介绍了为什么单条记录查找返回一个数组?(Rails 初学者)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对返回单个对象的模型进行了 where 操作.但我似乎无法在对象表示法中使用它(它似乎返回一个数组,对象位于 [0]).

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]

推荐答案

因为有时你不知道一个查询应该返回多少个对象,所以为了一致性你总是得到一个数组.

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

获取单个对象使用

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

如果您要查找模型的主 ID,也可以使用

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

store = Store.find(some_id)

如果找不到对象,它将引发 RecrodNotFound 异常(默认情况下由 rails 作为 404 处理).

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

这篇关于为什么单条记录查找返回一个数组?(Rails 初学者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆