在this tutorial中,我看到他们使用DELETE
操作的路由助手:<%= link_to "delete", article_path(@article), method: :delete %>
。但是,当我尝试使用类似的路径助手删除注释时,它不起作用:
<p><%= comment.body %><%= link_to article_comment_path(comment.id), method: :delete, data: {confirm: 'Are you sure?'} do %>
<button type="button" class="close" aria-hidden="true">×</button>
<% end %></p>
为什么它不起作用?这是我运行rake routes
时得到的结果。该教程说明前缀列中的名称&#34;滴入&#34;。所以带有空前缀的行从最接近的上一个前缀获得前缀。所以不是article_comment_path(<id>)
正确的路线助手吗?
我得到的错误是ActionView::Template::Error (No route matches {:action=>"show", :controller=>"comments", :id=>nil, :article_id=>4, :format=>nil} missing required keys: [:id]):
,因此它尝试转到show
操作而不是destroy
操作。
~/practice/blog >> rake routes
Prefix Verb URI Pattern Controller#Action
root GET / articles#index
article_comments GET /articles/:article_id/comments(.:format) comments#index
POST /articles/:article_id/comments(.:format) comments#create
new_article_comment GET /articles/:article_id/comments/new(.:format) comments#new
edit_article_comment GET /articles/:article_id/comments/:id/edit(.:format) comments#edit
article_comment GET /articles/:article_id/comments/:id(.:format) comments#show
PATCH /articles/:article_id/comments/:id(.:format) comments#update
PUT /articles/:article_id/comments/:id(.:format) comments#update
DELETE /articles/:article_id/comments/:id(.:format) comments#destroy
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
答案 0 :(得分:1)
删除嵌套资源时,必须同时指定两个资源ID。在您的代码中,将article.id
添加到article_comment_path
您的观看代码应该看起来像:
<p><%= comment.body %><%= link_to article_comment_path(article.id, comment.id), method: :delete, data: {confirm: 'Are you sure?'} do %>
<button type="button" class="close" aria-hidden="true">×</button>
<% end %></p>