gpt4 book ai didi

ruby-on-rails - rails : Why does find(id) raise an exception in rails?

转载 作者:行者123 更新时间:2023-12-03 04:37:16 24 4
gpt4 key购买 nike

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

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

这是为什么?

最佳答案

因为这就是架构师希望 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.

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

关于ruby-on-rails - rails : Why does find(id) raise an exception in rails?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/831347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com