You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Flash通知替代ActiveRecord::RecordNotFound错误并刷新页面?

解决Rails中用Flash通知替代RecordNotFound错误页面的方法

针对你遇到的场景,直接在CheckoutController的new动作里捕获异常即可,具体步骤如下:

1. 修改CheckoutController代码

给new方法加上异常捕获逻辑,触发错误时设置Flash提示并重定向回选计划页面:

class CheckoutController < ApplicationController
  def new
    @plan = Plan.find(params[:plan])
  rescue ActiveRecord::RecordNotFound
    flash[:alert] = "请先选择一个有效的订阅计划"
    redirect_to choose_plan_new_path
  end
end

2. 在页面显示Flash通知

确保你的选计划页面(或全局布局文件)里有展示Flash消息的代码,比如用ERB实现:

<% if flash[:alert] %>
  <div class="alert-error"><%= flash[:alert] %></div>
<% end %>

如果想让整个应用统一处理这类异常,也可以在ApplicationController里全局捕获:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :handle_missing_record

  private

  def handle_missing_record
    flash[:alert] = "请求的资源不存在,请先选择一个订阅计划"
    redirect_to choose_plan_new_path
  end
end

这样用户未选择计划就点击结账按钮时,会自动跳回选计划页面并看到提示,不会再出现错误页面。

内容的提问来源于stack exchange,提问作者Emil Ståhl Myllyaho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:45:41