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.
I had similar issue but with '.js' extension. To solve I did the following in the view:
<%= params.except!(:format) %> <%= will_paginate @posts %>
You can add a
before_filter
in your controller to set the request format tojson
:This will set all response format to
json
. If you want to allow other formats, you could check for the presence offormat
parameter when settingrequest.format
, for e.g:It's just:
You can use
format.any
:Of course:
You should probably put this in a root controller for your API.