Hi:
I am following the rails 3 user guide,the blog application.
And I want to make the comment resources editable(and both the create/update form will be displayed in the post/show page),so I try to make the following modifiation(the core):
CommentController.rb: class CommentsController < ApplicationController def edit
@post=Post.find(params[:post_id])
@comments=Comment.all
@comment = Comment.find(params[:id])
render "/posts/show"
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
respond_to do |format|
if @comment.save
format.html { redirect_to post_path @post, notice: 'Comment was successfully saved.' }
format.json { head :no_content }
else
format.html { render "posts/show" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
def update
@post=Post.find(params[:post_id])
@comment = Comment.find(params[:id])
respond_to do |format|
if @comment.update_attributes(params[:comment])
format.html { redirect_to post_path(@post), notice: 'Comment was successfully updated.' }
format.json { head :no_content }
else
format.html { render "posts/show" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end end
post/show.erb.html:
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<tr>
<td><%= comment.commenter %></td>
<td><%= comment.body %></td>
<td><%= link_to 'Edit', edit_post_comment_path(@post,comment) %></td>
<td><%= link_to 'Destroy', post_comment_path(@post,comment), confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
Add a comment:
<%= form_for([@post,@comment]) do |f| %><% if @comment.errors.any? %>
<h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% @comment.errors.full_messages.each do |msg| %>
<li>
<%= msg %>
</li>
<% end %>
</ul>
<%= f.text_field :commenter %>
<%= f.label :body %>
<br />
<%= f.text_area :body %>
routes.rb resources :posts do
resources :comments end
The above codes seems work at first,since I can CURD for posts and the nested comments.
However when I create a new comment,if there was any errors in the user input(for example minimum requirement),I will meet the error:
No route matches {:action=>“edit”, :controller=>“comments” …
When I remove the lines: <%= link_to ‘Edit’, edit_post_comment_path(@post,comment) %> <%= link_to ‘Destroy’, post_comment_path(@post,comment), confirm: ‘Are you sure?’, method: :delete %>
It will pass, and this error will not occur when I update a comment.
So I wonder why?
BTW,I am afraid I can not express clearly,so I upload the source codes,I hope someone can do me a favor and check it. Thanks.
Bnlog.zip (405 KB)