找到()与零时,没有记录 [英] find() with nil when there are no records
本文介绍了找到()与零时,没有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我目前的铁轨程序,当我使用类似
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
我可以得到零,而不是提高异常,所以当我做这样的事情:
Can I get nil instead of raising exception so when I do something like :
unless user = Challenge.find(10)
puts "some error msg"
end
我只是想获得零时,有没有记录,我不希望使用开始/救援
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:
Challenge.find_by(id: 10)
这篇关于找到()与零时,没有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文