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 seem 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 %>
routes.rb
ActionController::Routing::Routes.draw do |map|
map.resources :posts, :has_many => :comments
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
meagar is on the right path, but since this is a nested route you have to do:
<%= link_to 'Destroy', [@post, comment], ... %>
So, you are passing the comment and the post and letting rails figure out the route based on your definitions.
In _comments.html.erb
, change your link_to
to
<%= link_to 'Destroy', comment, ... %>
IE, pass it the comment
itself, not the entire @comments
array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With