xxjjnn
xxjjnn

Reputation: 15269

rails respond_to in controller rescue block

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.

Upvotes: 1

Views: 1827

Answers (3)

Johan Donado B.
Johan Donado B.

Reputation: 285

I have same issue. I had to use request.format to determine the request format.

Upvotes: 0

jimworm
jimworm

Reputation: 2741

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}

Upvotes: 1

Ahmed Samir Shahin
Ahmed Samir Shahin

Reputation: 558

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.

Upvotes: 2

Related Questions