I am new to Ruby. I am writing a Restful API application using Rails 4. How can I return a 404 JSON not found string when the record is not found?
I found a number of posts but no luck, only for Rails 3.
In my controller I can caught the exception
def show
country = Country.find(params[:id])
render :json => country.to_record
rescue Exception
render :json => "404"
end
But I want a generic one to capture all the not found resources.
To return a 404 header, just use the :status option for the render method. If you want to render the standard 404 page you can extract the feature in a method. If you want the action to render the error page and stop, simply use a return statement.
JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser: render json: @product. You don't need to call to_json on the object that you want to render.
Use rescue_from
. See http://guides.rubyonrails.org/v2.3.11/action_controller_overview.html#rescue
In this instance 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With