开发者

rails-3, new comment form from a polymorphic association, accepts form submission but doesn't display submited data

I have a polymorphic comment model and on the show.html.erb for the posts_controller,i have a link 'add comments', where you can click to comment on a post. When you click the link, 开发者_如何转开发the 'new comment form' comes up but when you submit the form, the comment doesn't display or show up anywhere in the app.Here is the gist with some view files and controllers: https://gist.github.com/828400 and here is the model, schema.rb and log file: https://gist.github.com/828447, thanks.


If you look at app/views/comments/_form.html.erb you'll notice that it builds a form using

[@post, Comment.new]

This means that it works correctly when you create a comment directly from a PostsController view as @post is set correctly. This means that the form builder sets the form's action to /posts/5/comments (where the 5 is taken from @post.id), thus setting the post_id param which the CommentsController looks for in CommentsController#get_parent.

However, when you click on 'Add a comment' or 'Add a reply' you are in the CommentsController, which sets a variable called @parent. That means that the form builder sets the form's action to /comments (since @post is nil), which means when you submit the form both the post_id and comment_id params are nil.

What this means that it reaches this line in CommentsController#get_parent:


redirect_to root_path unless defined?(@parent)

which means that your form contents are silently discarded.

The easiest way to get the forms to work correctly is to make the following changes:


#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

-  
+  

As you'll see, it means that the form looks for the @parent object (instead of @post), which then gets set by PostsController & CommentsController.

As an aside, you could consider making the following changes to tighten up your code:


-  redirect_to root_path unless defined?(@parent)
+  redirect_to root_path unless @parent

If @parent is not defined it will return nil, which is considered false.


-  return @post if defined?(@post)
-  @post = commentable.is_a?(Post) ? commentable : commentable.post
+  @post ||= commentable.is_a?(Post) ? commentable : commentable.post

Also, you call Comment.new in your views. Generally, initializing object should be done in a controller, and views should be limited to presentation logic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜