如何在Rails 4中返回404 JSON格式?

Kit*_* Ho 5 ruby-on-rails-4

我是Ruby的新手.我正在使用Rails 4编写Restful API应用程序.如果找不到记录,如何返回404 JSON not found字符串?

我找到了一些帖子,但没有运气,仅适用于Rails 3.

在我的控制器中,我可以发现异常

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

但我想要一个通用的捕获所有未找到的资源.

hol*_*igm 16

使用rescue_from.请参阅http://guides.rubyonrails.org/v2.3.11/action_controller_overview.html#rescue

在这种情况下使用类似的东西:

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
Run Code Online (Sandbox Code Playgroud)


Sre*_*hGS -1

做:

def show
  country = Country.find(params[:id])
  render :json => country.to_record
rescue Exception
  render :json => 404_json_text, :status => 404
end
Run Code Online (Sandbox Code Playgroud)