当没有记录时 find() 为 nil [英] find() with nil when there are no records
本文介绍了当没有记录时 find() 为 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我当前的 rails 程序中,当我使用类似
In my current rails program when I use something like
user = User.find(10)
当没有 ID=10 的用户时,我会有如下异常:
When there is no user with ID=10 , I will have exception like :
ActiveRecord::RecordNotFound: Couldn't find User with ID=10
我可以得到 nil 而不是引发异常,所以当我做这样的事情时:
Can I get nil instead of raising exception so when I do something like :
unless user = Challenge.find(10)
puts "some error msg"
end
我只想在没有记录并且不想使用 begin/rescue 时获得 nil
I just want to get nil when there is no records and I don't want to use begin/rescue
谢谢
推荐答案
是的,只需:
Challenge.find_by_id(10)
对于 Rails 4 和 5:
For Rails 4 and 5:
Challenge.find_by(id: 10)
这篇关于当没有记录时 find() 为 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文