I\'m trying to build an API in rails 4, and am having an issue where rails returns a 500 error instead of a 406 when using respond_to :json
and trying to access
You can set it by having a before filter that sets the request to JSON explicitly.
request.format = :json
I'm a bit late to this but regarding your comment to this answer:
I want all responses to be JSON
The easiest solution would be:
respond_to do |format|
format.all { render :json => @posts }
end
In Rails 4, you need to pass a lambda to enforce the constraint on a route.
Unfortunately, this will NOT work because it will still try to serve up (or attempt to serve up) an html template since the format is an optional parameter:
resources :posts, constraints: { format: 'json' }
This DOES work (uses the lambda):
resources :posts, constraints: lambda { |req| req.format == :json }
See the second (final) note in this section of the Rails guide.
As you are using a before_filter, you will have a 406 Not Acceptable if a request for a format is made which is not defined.
Example:
class SomeController < ApplicationController
respond_to :json
def show
@record = Record.find params[:id]
respond_with @record
end
end
The other way would be to add a before_filter to check for the format and react accordingly.
Example:
class ApplicationController < ActionController::Base
before_filter :check_format
def check_format
render :nothing => true, :status => 406 unless params[:format] == 'json'
end
end
But i think, you can just do it:
respond_to do |format|
format.json { render :json => @posts }
end
Further informations: http://guides.rubyonrails.org/layouts_and_rendering.html