Rails 4 - Respond only to JSON and not HTML

前端 未结 10 1204
栀梦
栀梦 2020-12-08 02:59

I\'m trying to build an API in rails 4, and am having an issue where rails returns a 500 error instead of a 406 when using respond_to :json and trying to access

10条回答
  •  天命终不由人
    2020-12-08 03:32

    As you are using a before_filter, you will have a 406 Not Acceptable if a request for a format is made which is not defined.

    Example:

    class SomeController < ApplicationController
      respond_to :json
    
    
      def show
        @record = Record.find params[:id]
    
        respond_with @record
      end
    end
    

    The other way would be to add a before_filter to check for the format and react accordingly.

    Example:

    class ApplicationController < ActionController::Base
      before_filter :check_format
    
    
      def check_format
        render :nothing => true, :status => 406 unless params[:format] == 'json'
      end
    end
    

    But i think, you can just do it:

    respond_to do |format|
      format.json { render :json => @posts }
    end
    

    Further informations: http://guides.rubyonrails.org/layouts_and_rendering.html

提交回复
热议问题