2013-12-17 29 views
0

在視頻控制器的更新動作,我已經寫 - >第一個參數不能包含零或爲空上呈現

def update 
    if current_user.video.update_attributes(video_params) 
     flash[:success] = "Video App Updated!" 
     redirect_to root_url 
    else 
     render :edit 
    end 
    end 

然而,渲染:編輯部分似乎被扔出來的錯誤。它說:

First argument in form cannot contain nil or be empty 
Extracted source (around line #6): 


    <div class="row"> 
    <div class="span6 offset3"> 
     <%= form_for(@video) do |f| %> # line 6 

我假設我不完全理解渲染正在做什麼。這是我編輯動作的樣子 - >

def edit 
    @video = current_user.video 
    end 

你們認爲什麼?仍然是小白,非常感謝:)

+0

解釋我想你是不是在「@video」變量 – Jeet

+0

嘿米希爾得到任何價值。雖然這是奇怪的部分。如果我只是加載編輯視圖,一切正常。但是,一旦我更新並通過渲染,它就不再給@video任何值。 –

回答

0

render :edit將顯示edit.html.erb視圖,但edit操作未執行。 edit.html.erb預計在update操作中未設置@video變量,這就是爲什麼您有此錯誤。有2個解決方案:

設置@video變量在update_action

def update 
    @video = current_user.video 
    if @video.update_attributes(video_params) 
    flash[:success] = "Video App Updated!" 
    redirect_to root_url 
    else 
    render :edit 
    end 
end 

重定向到edit行動時,更新失敗

def update 
    if current_user.video.update_attributes(video_params) 
    flash[:success] = "Video App Updated!" 
    redirect_to root_url 
    else 
    flash[:alert] = current_user.video.errors.full_messages.join('\n') 
    redirect_to :action => :edit, :id => current_user.video.id 
    end 
end 

如果edit是複雜的,第二種解決方案會更好,因爲它避免了重複。就你而言,第一個解決方案也是很好的。

renderredirect_to之間的差額,Guide Layouts and Rendering in Rails 2.3.2

+1

重定向不是很好的解決方案,因爲它不會以這種方式顯示驗證錯誤。 –

+2

@MarekLipka你說得對。我已經添加了一條Flash消息來解決這個問題,但這是一個骯髒的解決方案。第一種解決方案更好。 – Baldrick

+1

如果編輯很複雜,我會考慮將其邏輯提取爲其他方法,而不是通過引入重定向來修改應用程序流。 –

-1

我有相同類型的條件,我已經這樣做了。和它在我的情況

def update 
    @video = current_user.video 
    respond_to do |format| 
    if @video.update_attributes(video_params) 
     format.html { redirect_to root_url } 
    else 
     format.html { render :edit } 
    end 
    end 
end 
+0

感謝Mihir。我可以問一下,爲什麼要寫respond_to | format | ? –

+0

如果我們需要不同格式的結果,那麼我們使用respond_to fo | format |樣式。我的意思是在js格式或json格式等... – Jeet

1

工作你不設置@video變量上update動作,所以它的nil。你應該有:

def update 
    @video = current_user.video 
    if current_user.video.update_attributes(video_params) 
    flash[:success] = "Video App Updated!" 
    redirect_to root_url 
    else 
    render :edit 
    end 
end 

你應該記住,在控制器渲染其他行動的模板不運行動作的代碼。所以,如果你有

render :edit 

部分edit將呈現,但控制器代碼進行這個操作(設置@video)將不會運行。

+0

謝謝Marek!你一直在幫我整整一天:) –

相關問題