[英]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.