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

一个人想着一个人 提交于 2019-11-28 23:15:39

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

You can use format.any:

def action
  respond_to do |format|
    format.any { render json: your_json, content_type: 'application/json' }
  end
end

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

It's just:

render formats: :json

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!