Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Respond only to JSON and not HTML

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 the html version.

Here's an example controller demonstrating the problem:

class PostsController < ApplicationController   respond_to :json    def index     @posts = Post.all   end end 

I also have a jbuilder view for index that works when accessing via JSON. If I try accessing the route without the JSON extension, It attempts to load the HTML template (which doesn't exist) and returns a 500 error, instead of just rendering JSON or returning a 406 error.

What could be causing this? Cheers for any help.

like image 727
Tom Brunoli Avatar asked Feb 24 '14 03:02

Tom Brunoli


1 Answers

I believe there are 2 parts here:
1) json only requests in rails
2) json only responses in rails

1) Configure your application controller to ensure json requests only

# app/controller/application_controller.rb   before_action :ensure_json_request    def ensure_json_request     return if request.format == :json   render :nothing => true, :status => 406   end   

2) Configure your Rails API routes to ensure json responses only

# config/routes.rb   MyApp::Application.routes.draw do     namespace :api, constraints: { format: 'json' } do       namespace :v1 do         resources :posts       end     end   end   
like image 133
csi Avatar answered Sep 29 '22 11:09

csi