2011-03-03 63 views
7

我有一個簡單的視頻模型在我的Rails應用程序has_many評論。我在視頻的展示頁面上顯示這些評論。當我提交表格時,一切正常;但是,如果評論模型中存在驗證錯誤,那麼我的系統就會爆炸。如果評論模型中存在驗證錯誤,我只想再次呈現視頻的展示頁面,並顯示驗證錯誤樣式。我如何在創建操作中執行此操作?非常感謝!何處渲染評論控制器在Rails模型驗證失敗?

class CommentsController < ApplicationController 
    def create 
    @video = Video.find(params[:video_id]) 
    @comment = @video.comments.build(params[:comment]) 
    if @comment.save 
     redirect_to @video, :notice => 'Thanks for posting your comments.' 
    else 
     render # what? What do I render in order to show the video page's show action with the validation error styling showing? Please help! 
    end 
    end 
end 

回答

10

要做到這一點,你必須渲染一個模板:

class CommentsController < ApplicationController 
    def create 
    @video = Video.find(params[:video_id]) 
    @comment = @video.comments.build(params[:comment]) 
    if @comment.save 
     redirect_to @video, :notice => 'Thanks for posting your comments.' 
    else 
     render :template => 'videos/show' 
    end 
    end 
end 

請記住,你必須聲明任何實例變量(如@video)#創建CommentsController內動作也是如此,因爲VideosController#show動作不會運行,模板只會被渲染。例如,如果您的VideosController#show操作中有@video_name變量,則必須將相同的@video_name實例變量添加到CommentsController#create操作中。

+0

太棒了,非常感謝! – agentbanks217 2011-03-03 01:16:45

7

我有同樣的問題。我認爲你的問題是Rails validation over redirect的重複(最近也複製了custom validations errors form controller inside other parent controller rails 3.1)。

與潘Thomakos上述解決方案的問題是,如果VideosController#show有比它的代碼不平凡的量更多,那麼你將無法從videos/show模板呈現在不違反乾燥的原則。這是related discussion

的Railscasts成名This post from Ryan Bates建議你可以存儲在@video閃光燈跨越重定向堅持它;然而,當我嘗試這樣做時,它會作爲正確課程的一個實例出現,但它沒有您期望的任何超類 - 最重要的是ActiveRecord::Base。起初我想也許他的建議是過時的(它是在2006年寫的)。然而,2009年10月編寫的Rails validation over redirect的答案之一提倡使用相同的方法,儘管通過自定義clone_with_errors方法,該方法需要模型實例的淺表副本以避免深層對象出現問題。但即使採用這種方法,依賴超類的任何方法都不起作用。我猜這是對象被序列化到閃存然後反序列化的結果。我發現page written in 2007 which advocates against storing model object instances in the session

我還發現一個good argument in the formtastic google group pointing out that redirecting on validation failure is not the Rails Way,可能是一個壞主意。但是,在涉及多個控制器的情況下,這仍然不能提供好的解決方案。也許Cells可以用來解決上述干擾問題。

否則我想唯一的答案是堅持持久的簡單數據,如對象ID,錯誤消息字符串,等等。