Home > front end >  Flash a notificaton instead of error when I get ActiveRecord::RecordNotFound?
Flash a notificaton instead of error when I get ActiveRecord::RecordNotFound?

Time:07-26

Is it possible to refresh page and flash a notification to handle an error? I'm getting this error on my "choose_plan#new" page if the user presses the "checkout#new" button without selecting a plan. I'd prefer to show a nofication instead of only making my button work if they've selected a plan.

The error:

ActiveRecord::RecordNotFound (Couldn't find Plan without an ID):

My code:

class ChoosePlanController < ApplicationController
  def new
    @plans = Plan.all

class CheckoutController < ApplicationController
  def new
    @plan = Plan.find(params[:plan])

I'm using rails 7.0.1 and ruby 3.1.2

CodePudding user response:

You can use find_by which doesn't raise an error and will return nil if nothing is found.

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

CodePudding user response:

rescue the error and flash a notice.

class CheckoutController < ApplicationController
  def new
    begin
      @plan = Plan.find(params[:plan])
    rescue ActiveRecord::RecordNotFound => e
      flash.notice = e
    end

    ...
  end
end

You'll probably also want to render something.

Alternatively, you can use where and first instead of find. This will not raise an error, then check if there is a plan.

class CheckoutController < ApplicationController
  def new
    @plan = Plan.where(id: params[:plan]).first

    if @plan
      ...
    else
      flash.notice = "Plan not found"
    end
  end
end

  • Related