检查Rails控制器中是否存在记录

Joh*_*ith 0 ruby-on-rails ruby-on-rails-3

我想检查设置表中是否存在id为2的条目,如果不存在,我想要将用户重定向到setting_new_path.我的代码看起来像这样:

 def index
if Setting.find(2).present?
@patients = Patient.all
@patients_drucken = Patient.drucken

@anrede = Setting.find(1).anrede

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @patients }
end
else
  redirect_to new_setting_path
end
end
Run Code Online (Sandbox Code Playgroud)

但不知怎的,我得到了错误:

Couldn't find Setting with id=2
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这显示为错误!我的意思是在它没有定义的情况下,重定向到new_setting_path!是什么让我错了?

Kyl*_*yle 7

使用存在?检查记录存在:

if Setting.exists?(2)
Run Code Online (Sandbox Code Playgroud)