【问题标题】:Trying to delete comments in Rails尝试在 Rails 中删除评论
【发布时间】:2015-08-12 03:53:21
【问题描述】:

我正在尝试通过构建一个简单的博客来学习 Rails。按照教程,我已经可以使用 AJAX 添加 cmets。但是,现在我正在尝试使删除 cmets 成为可能,但它不起作用。我不断收到错误消息,例如“没有路线匹配 [GET]“/posts/1/cmets/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 %>

还有 cmets 控制器:

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'-action 中找到我的评论。

【问题讨论】:

  • 您的application.js 文件中有//= require jquery_ujs 行吗?
  • 链接问题的答案是“使用 button_to 而不是 link_to”。也应该适用于 rails 4。
  • @bdares 谢谢!我刚刚尝试用“button_to”替换“link_to”,但随后出现此错误:“param is missing or the value is empty: comment Extracted source (about line #25): def comment_params params.require(:comment).permit (:body) 结束结束

标签: ruby-on-rails ruby


【解决方案1】:

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

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

【讨论】:

  • 此外,一旦启动并运行它,您需要将 remote: true 添加到 link_to 帮助程序
  • 非常感谢!这样做并使用 button_to 而不是 link_to 使它工作!
猜你喜欢
  • 2021-10-02
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多