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
class Topic < ActiveRecord::Base
has_many :posts, dependent: :destroy
end
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :user
belongs_to :topic
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
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
link_to "Delete", [@topic, @post], method: :delete, data: {confirm: "Are you sure you want to delete this ?"}
答案 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
祝你好运!