Creating a Blog ruby on Rails - Problem Deleting Comments

Posted by bgadoci on Stack Overflow See other posts from Stack Overflow or by bgadoci
Published on 2010-04-12T03:19:51Z Indexed on 2010/04/12 3:23 UTC
Read the original article Hit count: 568

Filed under:
|

As I always type I am new to rails and programming in general so go easy. Thanks in advance.

I have successfully followed the initial tutorial from Ryan Bates on how to build a weblog in 15 minutes. If you don't know this tutorial takes you through creating posts and allowing for comments on those post. It even introduces AJAX through the creating and displaying comments on the posts show.html.erb page. All works great.

Here's the hiccup, when Ryan takes you though this tutorial he clears out the comments_controller and only shows the code for creating comments. I am trying to add back the ability to edit and destroy comments. Can't see to get it to work, keeps deleting the actual post not the comment (log shows that I keep sending DELETE request to PostsController). Here is my code:

class CommentsController < ApplicationController
 def create
   @post = Post.find(params[:post_id])
   @comment = @post.comments.create!(params[:comment])
   respond_to do |format|
     format.html { redirect_to @post }
     format.js
   end
 end

 def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html { redirect_to(posts_url) }
      format.xml  { head :ok }
    end
  end
end

/views/posts/show.html.erb

    <%= render :partial => @post %>

    <p>
        <%= link_to 'Edit', edit_post_path (@post) %> |
        <%= link_to 'Destroy', @post, :method => :delete, :confirm => "Are you sure?" %> |
        <%= link_to 'See All Posts', posts_path %>
    </p> 

    <h2>Comments</h2>
    <div id="comments">
        <%= render :partial => @post.comments %>
    </div>

    <% remote_form_for [@post, Comment.new] do |f| %>
        <p>
            <%= f.label :body, "New Comment" %><br/>
            <%= f.text_area :body %>
        </p>
        <p>

<%= f.submit "Add Comment" %></p>
<% end %>

/views/comments/_comment.html.erb

<% div_for comment do %>
    <p>
        <strong>Posted <%= time_ago_in_words(comment.created_at) %> ago
        </strong><br/>
        <%= h(comment.body) %><br/>
        <%= link_to 'Destroy', @comments, :method => :delete, :confirm => "Are you sure?" %>
    </p>
<% end %>

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby