0

사용자가 제출 한 URL이 지정된 URL로 리디렉션되기를 원하는 레일스의 POST, PUT 또는 DELETE 액션에 사용자가 제출하는 양식이 자주 있습니다. 성공. 나는 보통 /users과 같은 경로로 to이라는 숨겨진 추가 매개 변수를 만듭니다. 따라서 양식 제출이 실패하면 양식에 그대로 남아 있지만 성공하면 브라우저는 /users으로 리디렉션됩니다.레일에서 POST 한 후 지정된 URL로 리디렉션

I는 자동으로이 매개 변수에 대한보고 양식 제출은 어떤 컨트롤러/액션에 성공하면 항상로 리디렉션하고 싶습니다. 에 after_action 안에 넣습니까?

class ApplicationController < ActionController::Base 
    after_action :redirect_if_success 

    private 
    def redirect_if_success 
    redirect_to params[:to] if params[:to] 
    end 
end 

POST, PUT 또는 DELETE 작업 인 경우 요청 개체를 확인할 수 있습니다. 제출이 성공했는지 어떻게 알 수 있습니까? after_action에있는 redirect_to은 양식 컨트롤러에서 redirect_to을 대체합니까?

답변

0

나는 해결책이 응용 프로그램 컨트롤러에서 개인 메서드 redirect_if_success를 정의하지만 동작에서 직접 호출한다고 생각합니다. 예 :

class ApplicationController < ActionController::Base 

    private 
    def redirect_if_success(default_ur) 
    redirect_to params[:to] || default_url 
    # or similar logic 
    end 
end 

class UserController < ApplicationController::Base 

    def create 
    redirect_if_success("/users") if @user.save 
    end 
end 
0

나는 도우미 메서드

def redirect_to_location 
    redirect_to params[:to] && params[:to].present? 
end 

을 만들 것이며 내가이 동작을 원하는 각 작업에 명시 적으로 사용할 수 있습니다.

그러나 조금 실험 해 볼 수 있습니다. 이 논리를 after_action에 유지하려면 리디렉션해야하는지 여부를 알려주는 상태를 설정해야합니다.

def save 
    if @user.save 
    @follow_redirect = true 
    end 
end 

및 after_action 필터에 플래그를 @follow_redirect 확인 :

당신은 할 수 있습니다. 아주 예쁜 솔루션처럼 보이지는 않지만 작동 할 것입니다.

당신은 또한 당신이 이미 리디렉션 또는 작업 렌더링이 있는지 응답 변수를 검사을 시도 할 수 있습니다 : (이 일하는 것이 있는지 확실하지 않습니다를하지만 실험 재미)

그래서 당신은 확인할 수 있습니다 :

리디렉션/리디렉션하지 않은 경우 리디렉션해야 함 (작업은 게시/삭제/삭제)이고 매개 변수 [: to]가 있고

# this is not a copy-paste code but rather to demonstrate an idea 
class ApplicationController < ActionController::Base 
    after_action :redirect_to_location 

    protected 

    def is_redirectable? 
    %w{post put delete}.include?(request.method) && params[:to].present? 
    end 

    def already_redirected? 
    !response.status.nil? # not sure if it would work at all 
    end 

    def redirect_to_location 
    redirect_to params[:to] if is_redirectable? && !already_redirected? 
    end 
end