[英]rails-3, new comment form from a polymorphic association, accepts form submission but doesn't display submited data
我有一個多態評論模型,在posts_controller的show.html.erb上,我有一個“添加評論”鏈接,您可以在其中單擊以評論評論。 當您點擊鏈接時,會出現``新評論表單'',但是當您提交表單時,評論不會在應用程序中的任何位置顯示或顯示。以下是要點,其中包含一些視圖文件和控制器: https:// gist.github.com/828400 ,這是模型,schema.rb和日志文件: https : //gist.github.com/828447 ,謝謝。
如果查看app / views / comments / _form.html.erb,您會注意到它使用
[@post, Comment.new]
這意味着當您直接從PostsController視圖創建注釋時,因為@post設置正確,它可以正常工作。 這意味着表單構建器將表單的操作設置為/ posts / 5 / comments (其中5來自@ post.id),從而設置了CommentController在CommentsController#get_parent中查找的post_id參數。
但是,當您單擊“添加評論”或“添加回復”時,您將在CommentsController中,該控件將設置一個名為@parent的變量。 這意味着表單構建器將表單的操作設置為/ comments (因為@post為nil),這意味着當您提交表單時,post_id和comment_id參數均為nil。
這意味着它到達CommentsController#get_parent中的這一行:
redirect_to root_path unless defined?(@parent)
這意味着您的表單內容將被靜默丟棄。
使表格正常工作的最簡單方法是進行以下更改:
#app/controllers/posts_controller.rb:
def show
- @post = Post.find(params[:id])
+ @parent = @post = Post.find(params[:id])
end
#app/views/comments/_form.html.erb b/app/views/comments/_form.html.erb
-
+
如您所見,這意味着表單將查找@parent對象(而不是@post),然后由PostsController和CommentsController對其進行設置。
順便說一句,您可以考慮進行以下更改以加強代碼:
- redirect_to root_path unless defined?(@parent)
+ redirect_to root_path unless @parent
如果未定義@parent,它將返回nil,這被視為false。
- return @post if defined?(@post)
- @post = commentable.is_a?(Post) ? commentable : commentable.post
+ @post ||= commentable.is_a?(Post) ? commentable : commentable.post
此外,您在視圖中調用Comment.new。 通常,初始化對象應在控制器中完成,並且視圖應限於表示邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.