【发布时间】: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