Ruby-on-rails Rails:为什么 find(id) 在 rails 中引发异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/831347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:13:32  来源:igfitidea点击:

Rails: Why does find(id) raise an exception in rails?

ruby-on-railsactiverecord

提问by Kirschstein

Possible Duplicate:
Model.find(1) gives ActiveRecord error when id 1 does not exist

可能重复:
当 id 1 不存在时,Model.find(1) 给出 ActiveRecord 错误

If there is no user with an id of 1 in the database, trying User.find(1)will raise an exception.

如果数据库中没有 id 为 1 的用户,尝试User.find(1)将引发异常。

Why is this?

为什么是这样?

回答by runako

Because that's the way the architects intended find(id) to work, as indicated in the RDoc:

因为这是架构师希望 find(id) 工作的方式,如 RDoc 中所示:

Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). If no record can be found for all of the listed ids, then RecordNotFound will be raised.

按 id 查找 - 这可以是特定的 id (1)、id 列表 (1, 5, 6) 或 id 数组 ([5, 6, 10])。如果无法找到所有列出的 id 的记录,则将引发 RecordNotFound。

If you don't want the exception to be raised, use find_by_id, which will return nil if it can't find an object with the specified id. Your example would then be User.find_by_id(1).

如果您不想引发异常,请使用 find_by_id,如果找不到具有指定 id 的对象,它将返回 nil。你的例子就是User.find_by_id(1).

回答by John Topley

Further to runako's explanation, it's actually pretty useful to have the choice of whether an exception is raised or not. I'm working on a blog application and I wanted to add support for viewing the next or previous blog entry. I was able to add two instance methods to my Postmodel that simply return nilwhen you try to get the previous post when viewing the first post, or the next post when viewing the last post:

进一步解释 runako 的解释,选择是否引发异常实际上非常有用。我正在开发一个博客应用程序,我想添加对查看下一个或上一个博客条目的支持。我能够向我的Post模型添加两个实例方法,nil当您在查看第一篇文章时尝试获取上一篇文章或查看最后一篇文章时尝试获取下一篇文章时,这些方法仅返回:

def next
  Post.find_by_id(id + 1)
end

def previous
  Post.find_by_id(id - 1)
end

This avoids my helper code which conditionally generates the Previous Post/Next Post links from having to handle the RecordNotFoundexception, which would be bad because it would be using an exception for control flow.

这避免了我的辅助代码有条件地生成上一篇/下一篇文章链接,而不必处理RecordNotFound异常,这会很糟糕,因为它将使用异常进行控制流。