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

后端 未结 6 1622
青春惊慌失措
青春惊慌失措 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
    

提交回复
热议问题