0

respond_to not working inside controller rescue block:

def create
  respond_to do | format |
    format.json { render json: SomeManager.new(some_params).json }
    format.html do
      SomeManager.new(some_params)
      render :new, notice: 'it worked'
    end
  end
rescue => e
  respond_to do | format |
    format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
    format.html { render :new, alert: 'did not work because reasons' }
  end
end

^ Controller for API which can respond to API json uploads, or manual uploads using UI.

xxjjnn
  • 14,591
  • 19
  • 61
  • 94
  • ah... in my particular case this was only not working because of an elsewhere error, the upload of the file needed to be in the view `= form_tag({action: :create, format: 'html'}, multipart: true) do`, in that I specifically needed to add that the format is html – xxjjnn Jun 07 '17 at 10:27

2 Answers2

2

For better readability, use begin .. rescue like this instead:

def create
  respond_to do | format |
    begin
      format.json { render json: SomeManager.new(some_params).json }
      format.html do
        SomeManager.new(some_params)
        render :new, notice: 'it worked'
      end
    rescue => e
      format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
      format.html { render :new, alert: 'did not work because reasons' }
    end
  end
end

I think it shall work.

1

The rescue block isn't to blame. This would happen if your routes.rb is specified with an option like so:

resources :widgets, defaults: {format: :the_spanish_inquisition}
jimworm
  • 2,731
  • 18
  • 26