如何删除嵌套在帖子内的注释,该帖子嵌套在主题内?

时间:2014-12-05 03:19:42

标签: ruby-on-rails nested

我正在尝试删除嵌套在帖子中的注释。所述帖子嵌套在一个主题内。我对RoR很新,在提出问题之前尝试自己做事,真的需要帮助。我当前的设置会删除整个帖子而不是评论

的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

(型号)topic.rb

class Topic < ActiveRecord::Base
 has_many :posts, dependent: :destroy
end

(型号)post.rb

class Post < ActiveRecord::Base
 has_many :comments, dependent: :destroy
 belongs_to :user
 belongs_to :topic
end

(型号)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 

部分在views / posts / show

上呈现
link_to "Delete", [@topic, @post], method: :delete, data: {confirm: "Are you sure you want to delete this ?"}

2 个答案:

答案 0 :(得分:1)

你应该改变这个

link_to "Delete", [@topic, @post], method: :delete, data: {confirm: "Are you sure you want to delete this ?"}

到这个

link_to "Delete", [@post, @comment], method: :delete, data: {confirm: "Are you sure you want to delete this ?"}

因此,链接为您提供了一个类似posts /:post_id / comments /:id的路径,其中包含DELETE http方法。

评论的控制者:

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 

我刚刚更改了第一个redirect_to,因为我不知道你为什么要使用redirect_to [@ post.post,@ post]

答案 1 :(得分:0)

在views / posts / show上呈现的部分我希望删除整个帖子。

如果有一个评论视图,你可能会有类似这样的节目,路线更新为你的,我猜了一下:

link_to 'Delete', post_comment_path(@post, @comment), method: :delete, data: { confirm: 'Are you sure?' }

或者,如果您有评论的索引视图,则可能有效:

link_to 'Delete', comment, method: :delete, data: { confirm: 'Are you sure?' }

此外,Rails指南的这一部分可能会有所帮助:http://guides.rubyonrails.org/routing.html#nested-resources

祝你好运!