试图删除Rails

时间:2015-08-11 18:38:56

标签: ruby-on-rails ruby

我正在尝试通过构建一个简单的博客来学习Rails。继一个教程之后,我就可以用AJAX添加注释了。但是,现在我试图删除可能的注释,但它不起作用。我不断收到错误消息,例如“没有路线匹配[GET]”/ posts / 1 / comments / 3“”。

这些是我的路线:

post_comments_path  POST    /posts/:post_id/comments(.:format)  comments#create
post_comment_path   DELETE  /posts/:post_id/comments/:id(.:format)  comments#destroy
posts_path  GET     /posts(.:format)    posts#index
    POST    /posts(.:format)    posts#create
new_post_path   GET     /posts/new(.:format)    posts#new
edit_post_path  GET     /posts/:id/edit(.:format)   posts#edit
post_path   GET     /posts/:id(.:format)    posts#show
    PATCH   /posts/:id(.:format)    posts#update
    PUT     /posts/:id(.:format)    posts#update
    DELETE  /posts/:id(.:format)    posts#destroy
root_path   GET     /   posts#index 

这是我的routes.rb文件:

Rails.application.routes.draw do
  resources :posts do
    resources :comments, only: [:create, :destroy]
  end

  root 'posts#index'
end

_comment.html.erb:

<%= div_for comment do %>
  <p>
    <strong>
      Posted <%= time_ago_in_words(comment.created_at) %> ago
    </strong>
    <br/>
    <%= comment.body %>
  </p>
  <p>
    <%= link_to 'Delete', [comment.post, comment],
               :method => :delete,
               data: { confirm: 'Are you sure?' }
                %>
  </p>
<% end %>

评论控制员:

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

    def destroy
        @post = Post.find(params[:post_id])
        @comment = @post.comments.find(comment_params)
        @comment.destroy

        respond_to do |format|
            format.html { redirect_to @post }
            format.js
        end
    end

    private

    def comment_params
        params.require(:comment).permit(:body)
    end
end

感谢您的帮助!

更新:我确实必须将'link_to'更改为'button_to',但我也错误地在'destroy'中找到了我的评论,我必须修复它。

1 个答案:

答案 0 :(得分:0)

您正在尝试使用comment_params找到评论。

在您的销毁操作中,而不是@comment = @post.comments.find(comment_params),请尝试@comment = Comment.find(params[:id])