2013-12-07 51 views
0

以下代碼示例是在Ruby 1.9.3p484上運行的Rails 3.2.16應用程序的一部分。
每當創建新位置或更新位置時,應按照after_filter中的定義發送消息。使用mail_form傳遞郵件時的DoubleRenderError

class LocationController < InheritedResources::Base 

    respond_to :json 

    after_filter :notify_location_contact, only: [:create, :update] 

    def create 
    @location.user = current_user if current_user 
    create! 
    end 

    def update 
    update! 
    end 


    private 

    def notify_location_contact 
    message = MailForm.new 
    deliver_location_message(message) 
    end 

    def deliver_location_message(location_message) 
    begin 
     if location_message.deliver 
     render json: { message: "Successfully delivered" }, status: 201 
     else 
     render json: { error: "Delivery failure" }, status: 500 
     end 
    rescue => e 
     if e.is_a?(ArgumentError) 
     render json: { error: "Invalid Recipient" }, status: 422 
     else 
     render json: { error: e.message }, status: 500 
     end 
    end 
    end 

end 

該消息本身被髮送。雖然,deliver_location_message首先呈現「成功傳遞」塊,並在最後一塊呈現錯誤消息之後呈現。這會導致內部服務器錯誤:

Completed 500 Internal Server Error

AbstractController::DoubleRenderError - Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

爲了發送使用mail_form gem~> 1.5.0該消息。

DoubleRenderError似乎發生是因爲createupdate都在他們完成工作時呈現JSON響應。之後,.deliver呈現其JSON響應以通知成功或失敗。

回答

0

由於錯誤指出您需要在致電render後返回,因爲您在deliver_location_message(message)方法中有多次致電render。錯誤的原因是因爲Rails繼續執行直到方法結束,無論是渲染還是重定向。

請嘗試以下操作。請注意,每個render行上的return

def deliver_location_message(message) 
    begin 
     if message.deliver 
     # Here 
     return render json: { message: "Successfully delivered" }, status: 201 
     else 
     # Here 
     return render json: { error: "Delivery failure" }, status: 500 
     end 
    rescue => e 
     if e.is_a?(ArgumentError) 
     # Here 
     return render json: { error: "Invalid Recipient" }, status: 422 
     else 
     # Here 
     return render json: { error: e.message }, status: 500 
     end 
    end 
    end 

替代語法:

return render json: { message: "Successfully delivered" }, status: 201 

是:

render json: { message: "Successfully delivered" }, status: 201 and return 
+0

我試過了。雖然同樣的錯誤。 – JJD

+0

@JJD,你可以在你的問題中發表你的完整曲線嗎? – vee

+0

這是[stacktrace](http://pastebin.com/a5mZxfme)。 – JJD

相關問題