ruby-on-railscontrollerruby-on-rails-4.2

rails skip an after_action in a controller/method


In my controller I have an after_action block. I want to stop the after_action from running when the method in question fails.

Rails 4.2, ruby 2.2

Does anyone know how to do this in rails?

class MyController  < ApplicationController

  after_action only: :show do
    # do so and so
  end

  def show
    begin
      # something really bad happens here... My Nose!

    rescue => e 

      # how do I stop after_action from running?

      flash[:error] = 'Oh noes... Someone make a log report'
      redirect_to '/'
      return
    end

    # yarda yarda yarda

  end
end

Solution

  • I would do it like this. Set an instance variable if the the show action errors and check that variable in the after action:

    class MyController  < ApplicationController
    
      after_action only: :show do
        unless @skip_after_action
          # after action code here
        end
      end
    
      def show
        begin
          # something really bad happens here...
        rescue => e 
          @skip_after_action = true
          flash[:error] = 'Oh noes... Someone make a log report'
          redirect_to '/'
        end
      end
    end