如果数据库为空,则处理ActiveRecord错误

时间:2022-03-29 23:18:52

I'm working on a rails 4 app, and i have the following controller code

我正在使用rails 4 app,我有以下控制器代码

 def index
  @issue = Issue.find(1)
  @sections = @issue.sections
  @articles = @issue.articles
 end

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?

如果数据库为空并且出现错误,则会中断:“无法找到id = 1的问题”。检查这个问题的正确方法是什么,如果数据库中没有任何内容,它不会引发错误?

3 个解决方案

#1


2  

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

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).

旁注:由于您试图通过id查找,因此您不一定需要.where部分;你可以简单地做:Issue.exists?(1)。

exists? documentation on APIDoc

存在?有关APIDoc的文档

#2


2  

In most cases such exception is expected and recommenced. For example, you can rescue it with a custom 404 page.

在大多数情况下,这种例外是预期的并且会重新开始。例如,您可以使用自定义404页面进行营救。

Anyway, if you really don't want that, you can use find_by method which will output nil if nothing found

无论如何,如果你真的不想那样,你可以使用find_by方法,如果没有找到,将输出nil

@issue = Issue.find_by(id: 1)

#3


2  

you can handle that exception in your controller

您可以在控制器中处理该异常

rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
def record_not_found
 flash[:alert] = "invalid information"
 redirect_to root_url
end

or you can use a where clause

或者您可以使用where子句

@issue = Issue.where(id: 1).first

now check for nil by

现在检查是否为零

@issue.nil?

#1


2  

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

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).

旁注:由于您试图通过id查找,因此您不一定需要.where部分;你可以简单地做:Issue.exists?(1)。

exists? documentation on APIDoc

存在?有关APIDoc的文档

#2


2  

In most cases such exception is expected and recommenced. For example, you can rescue it with a custom 404 page.

在大多数情况下,这种例外是预期的并且会重新开始。例如,您可以使用自定义404页面进行营救。

Anyway, if you really don't want that, you can use find_by method which will output nil if nothing found

无论如何,如果你真的不想那样,你可以使用find_by方法,如果没有找到,将输出nil

@issue = Issue.find_by(id: 1)

#3


2  

you can handle that exception in your controller

您可以在控制器中处理该异常

rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
def record_not_found
 flash[:alert] = "invalid information"
 redirect_to root_url
end

or you can use a where clause

或者您可以使用where子句

@issue = Issue.where(id: 1).first

now check for nil by

现在检查是否为零

@issue.nil?

相关文章