How do I remove a comment that is nested within a message nested within a topic?
I am trying to remove a comment nested inside a post. The specified post is nested inside the topic. I'm new to RoR and try to work on my stuff before asking a question, really need help here. My current setup deletes the entire post instead of a comment
routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users, only: [:update]
resources :topics do
resources :posts, except: [:index]
end
resources :posts, only: [] do
resources :comments, only: [:create, :destroy]
end
end
(model) topic.rb
class Topic < ActiveRecord::Base
has_many :posts, dependent: :destroy
end
(model) post.rb
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :user
belongs_to :topic
end
(model) comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
comment_controller
def destroy
@topic = Topic.find(params[:topic_id])
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
authorize @comment
if @comment.destroy
flash[:notice] = "Comment was removed"
redirect_to [@post.post, @post]
else
flash[:notice] = "There was an error removing comment"
redirect_to [@topic, @post]
end
end
part displayed on performances / messages / shows
link_to "Delete", [@topic, @post], method: :delete, data: {confirm: "Are you sure you want to delete this ?"}
+3
source to share
2 answers
you have to change this
link_to "Delete", [@topic, @post], method: :delete, data: {confirm: "Are you sure you want to delete this ?"}
to that
link_to "Delete", [@post, @comment], method: :delete, data: {confirm: "Are you sure you want to delete this ?"}
So the link gives you a path like posts /: post_id / comments /: id using the DELETE http method.
And the comment controller:
def destroy
@topic = Topic.find(params[:topic_id])
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
authorize @comment
if @comment.destroy
flash[:notice] = "Comment was removed"
redirect_to @post
else
flash[:notice] = "There was an error removing comment"
redirect_to [@topic, @post]
end
end
I just changed the first redirect_to because I don't know why you were using redirect_to [@ post.post, @post]
+1
source to share
The part displayed in views / posts / shows I expect to delete the entire entry.
If there is a comment view you might have something like this to show with an updated route to what you have, I assumed:
link_to 'Delete', post_comment_path(@post, @comment), method: :delete, data: { confirm: 'Are you sure?' }
alternately, if you have an indexed comment for comments, this might work:
link_to 'Delete', comment, method: :delete, data: { confirm: 'Are you sure?' }
Also, this section of the Rails manual might be helpful: http://guides.rubyonrails.org/routing.html#nested-resources
Good luck!
0
source to share