![](/img/trans.png)
[英]Why do I get this error ActiveRecord::RecordNotFound in LocationsController#index
[英]Flash a notificaton instead of error when I get ActiveRecord::RecordNotFound?
是否可以刷新页面和 flash 通知来处理错误? 如果用户在未选择计划的情况下按下“checkout#new”按钮,我会在“choose_plan#new”页面上收到此错误。 如果他们选择了一个计划,我更愿意显示一个通知,而不是只让我的按钮工作。
错误:
ActiveRecord::RecordNotFound (Couldn't find Plan without an ID):
我的代码:
class ChoosePlanController < ApplicationController
def new
@plans = Plan.all
class CheckoutController < ApplicationController
def new
@plan = Plan.find(params[:plan])
ActiveRecord::Base.transaction do
@subscription = Subscription.create!({
plan: @plan,
title: @plan.title,
我正在使用导轨 7.0.1 和 ruby 3.1.2
您可以使用find_by
,它不会引发错误,如果没有找到任何内容,将返回nil
。
def new
if params[:plan].blank?
redirect_to new_choose_plan_path, notice: "Please, select a plan."
return
end
@plan = Plan.find_by(id: params[:plan])
unless @plan
redirect_to new_choose_plan_path, notice: "No plan found."
return
end
# ...
end
class CheckoutController < ApplicationController
def new
begin
@plan = Plan.find(params[:plan])
rescue ActiveRecord::RecordNotFound => e
flash.notice = e
end
...
end
end
你可能还想渲染一些东西。
或者,您可以使用where
和first
而不是find
。 这不会引发错误,然后检查是否有计划。
class CheckoutController < ApplicationController
def new
@plan = Plan.where(id: params[:plan]).first
if @plan
...
else
flash.notice = "Plan not found"
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.