Rails 4 - Respond only to JSON and not HTML

前端 未结 10 1165
栀梦
栀梦 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:24

    You can set it by having a before filter that sets the request to JSON explicitly.

    request.format = :json

    0 讨论(0)
  • 2020-12-08 03:24

    I'm a bit late to this but regarding your comment to this answer:

    I want all responses to be JSON

    The easiest solution would be:

    respond_to do |format|
      format.all { render :json => @posts }
    end
    
    0 讨论(0)
  • 2020-12-08 03:26

    In Rails 4, you need to pass a lambda to enforce the constraint on a route.

    Unfortunately, this will NOT work because it will still try to serve up (or attempt to serve up) an html template since the format is an optional parameter:

    resources :posts, constraints: { format: 'json' }
    

    This DOES work (uses the lambda):

    resources :posts, constraints: lambda { |req| req.format == :json }
    

    See the second (final) note in this section of the Rails guide.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题