Rails 4 - How to render JSON regardless of requested format?

后端 未结 6 1541
青春惊慌失措
青春惊慌失措 2020-12-09 02:53

I\'d like a Rails controller (all of them, actually, it\'s an API) to render JSON always always.

I don\'t want Rails to return \"route not found\", or try and fail t

相关标签:
6条回答
  • 2020-12-09 03:22

    You can add a before_filter in your controller to set the request format to json:

    # app/controllers/foos_controller.rb
    
    before_action :set_default_response_format
    
    protected
    
    def set_default_response_format
      request.format = :json
    end
    

    This will set all response format to json. If you want to allow other formats, you could check for the presence of format parameter when setting request.format, for e.g:

    def set_default_response_format
      request.format = :json unless params[:format]
    end
    
    0 讨论(0)
  • 2020-12-09 03:22

    I tried the above solutions and it didn't solve my use case. In some of the controllers of my Rails 4.2 app, there was no explicit render called. For example, a service object was called and nothing was returned. Since they are json api controllers, rails was complaining with a missing template error. To resolve I added this to our base controller.

      def render(*args)
        options = args.first
        options.present? ? super : super(json: {}, status: :ok)
      end
    

    It's a large app I'm converting to Rails 5, so this is just a safety measure as I removed the RocketPants gem that seemed to do this automatically.

    As a note, my controllers inherit from ActionController::Base

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

    Of course:

    before_filter :always_json
    
    protected
    
    def always_json
      params[:format] = "json"
    end
    

    You should probably put this in a root controller for your API.

    0 讨论(0)
  • 2020-12-09 03:29

    It's just:

    render formats: :json
    
    0 讨论(0)
  • You can use format.any:

    def action
      respond_to do |format|
        format.any { render json: your_json, content_type: 'application/json' }
      end
    end
    
    0 讨论(0)
  • 2020-12-09 03:36

    I had similar issue but with '.js' extension. To solve I did the following in the view: <%= params.except!(:format) %> <%= will_paginate @posts %>

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