How can I return a 404 JSON format in Rails 4?

2020-07-08 07:12发布

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.

2条回答
forever°为你锁心
2楼-- · 2020-07-08 07:36

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
查看更多
做个烂人
3楼-- · 2020-07-08 07:47

Do:

def show
  country = Country.find(params[:id])
  render :json => country.to_record
rescue Exception
  render :json => 404_json_text, :status => 404
end
查看更多
登录 后发表回答