Rails 4 - How to render JSON regardless of request

2020-02-03 10:49发布

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 to find an HTML template, or return 406. I just want it to automatically and always render JSON, e.g. from a RABL or JBuilder view.

Is this possible? Related questions seem to have answers that have the aforementioned downsides.

5条回答
爷的心禁止访问
2楼-- · 2020-02-03 11:09

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

查看更多
我只想做你的唯一
3楼-- · 2020-02-03 11:21

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
查看更多
Summer. ? 凉城
4楼-- · 2020-02-03 11:27

It's just:

render formats: :json
查看更多
够拽才男人
5楼-- · 2020-02-03 11:28

You can use format.any:

def action
  respond_to do |format|
    format.any { render json: your_json, content_type: 'application/json' }
  end
end
查看更多
We Are One
6楼-- · 2020-02-03 11:30

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.

查看更多
登录 后发表回答