本文介绍了处理一个ActiveRecord错误,如果数据库是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我工作的一个轨道4应用程序,我有以下控制器code
I'm working on a rails 4 app, and i have the following controller code
def index
@issue = Issue.find(1)
@sections = @issue.sections
@articles = @issue.articles
end
打破,如果数据库是空的,出现错误:找不到问题与ID = 1。什么是正确的方式来检查这一种方式,如果没有在分贝它不会引发错误?
which breaks if the database is empty with the error: "Couldn't find Issue with id=1". What is the proper way to check for this in a way that if nothing is in the db it doesn't raise an error?
推荐答案
您可以使用一个方法是存在
活动记录的方法,像这样:
One method you can use is the exists?
active record method, like so:
@issue = Issue.where(id: 1)
if @issue.exists?
# do something if it exists
else
# do something if it is missing
end
附注:既然你试图查找 ID
,你不一定需要。凡
部分;你可以简单地做: Issue.exists(1)
Side note: Since you're attempting to find by id
, you don't necessarily need the .where
portion; you can simply do: Issue.exists?(1)
.
这篇关于处理一个ActiveRecord错误,如果数据库是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!