Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a 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 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.

like image 384
TheOneTeam Avatar asked Apr 28 '14 04:04

TheOneTeam


People also ask

How do I return a 404 in Rails?

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.

What is format JSON rails?

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.


1 Answers

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
like image 147
holodigm Avatar answered Sep 28 '22 05:09

holodigm