2013-04-12 37 views
2

我對發展(JSON)API階段,決定繼承我ApiControllerActionController::Metal到了速度優勢等處理的ActiveRecord :: RecordNotFound與ActionController的金屬::

所以我已經包括了一堆的模塊,使其工作。

最近我決定在記錄未找到時用空結果回覆。軌已經拋出從Model#find方法ActiveRecord::RecordNotFound,我一直試圖用rescue_from抓住它,寫這樣的事:

module Api::V1 
    class ApiController < ActionController::Metal 
    # bunch of included modules 

    include ActiveSupport::Rescuable 

    respond_to :json 

    rescue_from ActiveRecord::RecordNotFound do 
     binding.pry 
     respond_to do |format| 
     format.any { head :not_found } 
     end 
    end 
    end 
end 

打電話後,我簡單的動作

def show 
    @post = Post.find(params[:id]) 
end 

和執行永遠達不到rescue_from。它的投擲:

ActiveRecord::RecordNotFound (Couldn't find Post with id=1 

到我的日誌文件。

我一直在嘗試它,並在生產模式。服務器響應404,但響應正文爲標準HTML錯誤頁面爲JSON請求。

當我將遺傳從ActionController::Metal更改爲ActionController::Base時,它很有效。

您可能會注意到缺少respond_with調用。那是因爲我使用RABL作爲我的模板系統。

所以問題是:是否有機會使rescue_fromMetal一起工作或擺脫反應HTML?

回答

5

以下爲我工作:

class ApiController < ActionController::Metal 
    include ActionController::Rendering 
    include ActionController::MimeResponds 
    include ActionController::Rescue 

    append_view_path Rails.root.join('app', 'views').to_s 
    rescue_from ActiveRecord::RecordNotFound, with: :four_oh_four 

    def four_oh_four 
    render file: Rails.root.join("public", "404.html"), status: 404 
    end 
end 
+0

大。它幫助了我。抱歉遲了迴應。 – ck3g

相關問題