2017-04-06 3 views
0

나는 어떤 경우에도 로그 쇼 오류 후에 개체를 만들고 부울을 true로 설정하고 리디렉션하려고합니다.부울 값이 참인 경우 리디렉션을 제어하는 ​​방법은 무엇입니까?

누군가가 어떻게 알 수 있습니까?

class BrandsController < ApplicationController 

    def new 
    @brand = current_user.build_brand(params[:brand]) 
    end 

    def create 
    @brand = current_user.build_brand(params[:brand]) 


    if @brand.save 

     redirect_to "#{new_user_path}?branded=#{@current_user.branded[1]}" 

flash[:success] = "thank's".html_safe 
    end 

    end 
end 
+0

무엇이 오류입니까? –

+0

'@ brand.save'는 예외를 생성하는 것을하지 않는 한 부울입니다. – tadman

답변

0

구체적으로 무엇이 잘못되었는지는 확실치 않지만 적절한 레일스 스타일에서는 실제로 수행되지 않은 몇 가지 사항이 있습니다. 당신이 전부 if을 피할 수 있도록

class BrandsController < ApplicationController 
    before_action :build_brand, only: [ :new, :create ] 

    def new 
    end 

    def create 
    @brand.save! 

    flash[:success] = "Thanks!" 

    redirect_to new_user_path(branded: @current_user.branded[1]) 

    rescue ActiveRecord::RecordInvalid 
    render(action: :new) 
    end 

protected 
    def build_brand 
    @brand = current_user.build_brand(params[:brand]) 
    end 
end 

문제가 있다면 save!는 예외를 생성하여, 다음은 더 기존의 고쳐 써 졌던 버전이다. 그런 다음 양식을 다시 렌더링하여 저장할 수없는 경우를 처리 할 수 ​​있습니다. 중복 코드를 한 번 처리 할 수있는 before_action 처리기로 이동할 수도 있습니다.

flash[:success]을 참조 할 때 html_safe 호출을 템플릿으로 이동하십시오. 여기에서 벗어나는 것은시기 상조입니다. 경우에 따라 JSON 대신 HTML을 보내고 싶을 수도 있습니다.