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
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
I would suggest you to try gem 'active_model_serializers'
. Its really awesome and keeps clean.
ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception, if: Proc.new { |c| c.request.format != 'application/json' }
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end
Routes:
namespace :api, defaults: { format: :json } do
resource :posts
end
Posts Controller:
def index
render json: Post.all
end
To avoid loading the non-existent HTML template, set the default resource type as JSON in config/routes.rb:
resources :posts, :defaults => { :format => :json }
You can try this, as I was also facing this issue and now it is solved by using this solution.
class PostsController < ApplicationController
respond_to :json
def index
@posts = Post.all
render json: @posts
end
end
when you try a responses in json is beacuse you only need some properties i used this
@my_model=Model.select(:attributeN, :attributeN......, attributeN)
respond_to do |format|
format.json {
render json: @my_model
}
end
constraints
was not working for POST requests and then I tried defaults
it works for all.
namespace :api, :defaults => { :format => 'json' } do
namespace :v1 do
resources :users do
collection do
get 'profile'
end
end
post 'signup' => 'users#create'
post 'login' => 'user_sessions#create'
end
end