2013-12-07 7 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은 먼저 "Successfully delivered"블록을 렌더링하고 마지막 블록 이후에 오류 메시지를 렌더링합니다. mail_form gem~> 1.5.0가 사용하는 메시지를 전송하는 경우

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".

: 내부 서버 오류가 발생합니다.

DoubleRenderError는 createupdate이 모두 완료되면 JSON 응답을 렌더링하기 때문에 발생합니다. 그 후에 .deliver은 JSON 응답을 렌더링하여 성공 또는 실패를 알립니다.

답변

0

deliver_location_message(message) 메서드에서 render에 대한 호출이 여러 번 있기 때문에 오류가 발생 했으므로 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

다음은 [스택 추적] (http://pastebin.com/a5mZxfme)입니다. – JJD