How can I return 404 JSON format in Rails 4?

I am new to Ruby. I am writing a Restful API application using Rails 4. How can I return 404 JSON string not found when the record is not found?

I found some posts, but no luck, only for Rails 3.

In my controller I can catch an exception

def show country = Country.find(params[:id]) render :json => country.to_record rescue Exception render :json => "404" end 

But I want the shared one to capture all the unused resources.

+5
ruby-on-rails-4
Apr 28 '14 at 4:06 on
source share
2 answers

Use rescue_from . See http://guides.rubyonrails.org/v2.3.11/action_controller_overview.html#rescue

In this case, use something like:

 class ApplicationController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found private def record_not_found(error) render json: { error: error.message }, status: :not_found end end 
+13
Mar 27 '15 at 3:20
source share

do:

 def show country = Country.find(params[:id]) render :json => country.to_record rescue Exception render :json => 404_json_text, :status => 404 end 
-one
Apr 28 '14 at 4:12
source share



All Articles