2017-07-19 98 views
0

在創建過程中發生錯誤時,將調用呈現新操作。我需要顯示新的自定義佈局。而是顯示應用程序佈局。如何解決這個問題?呈現自定義佈局而不是應用程序佈局

def new 
    @user = User.new 
    render layout: 'theme_forest' 
end 

def create 
    @user = User.new(user_params) 

    respond_to do |format| 
    if @user.save 
    @user.add_role(COMPANY_ADMIN) 
    sign_in @user 
    format.html { redirect_to "/users", 
        notice: 'User was successfully created.' } 
    format.json { render json: @user, status: :created, 
        location: "/users" } 
    else 
    format.html { render :new } 
    format.json { render json: @user.errors, status: :unprocessable_entity } 
    end 
end 

+0

'在新動作中呈現佈局:'theme_forest''是正確的。你有什麼錯誤嗎? – Vishal

+0

嘗試將'format.html {render:new}'改爲'format.html {render:new,layout:'theme_forest'}' – Pavan

回答

2

正如我提到的,你應該改變

format.html { render :new } 

format.html { render :new, layout: 'theme_forest'} 

當錯誤發生時在創建過程中,使新的行動是 調用

說明:

沒有!當您使用render時,它只是加載模板(即new.html.erb)。其將不會調用/觸發對應的controller#method(即,new)。所以render layout: 'theme_forest'中的new方法在這種情況下永遠不會被稱爲

1

你的問題是,你講的不是用你的自定義佈局的渲染器。

在新操作中,您已正確添加render layout: 'theme_forest', 但是您在創建操作中沒有這樣做。

在你創建行動,在else塊

format.html { render :new } 
format.json { render json: @user.errors, status: :unprocessable_entity } 

render :new命令不調用你的新動作,它只是呈現new.html.erb模板,因此你需要在佈局選項添加到渲染方法,帕文的評論暗示,如果你想使用一個不同的佈局:

format.html { render :new, layout: 'theme_forest' } 
format.json { render json: @user.errors, status: :unprocessable_entity }