Rails: 无法将多个变量 id 传递给嵌套路由
Rails: Fail to pass multiple variable-ids to nested route
在我的项目中有 2 个嵌套资源:
Rails.application.routes.draw do
resources :posts do
resources :comments
end
root 'posts#index'
end
我正在使用部分 _comment.html.erb
渲染一组评论
<%= render partial: "comments/comment", collection: @post.comments %>
部分看起来像这样
<div class="comment_wrapper">
<p class="comment_name"><%= comment.name %></p>
<p class="comment_date"><%= comment.created_at %></p>
<p class="comment_body"><%= comment.body %></p>
<%= link_to "Delete comment", post_comment_path(@post.id, id: comment.id), method: :delete%>
</div>
问题出在 "Delete comment" link 中的嵌套路由。
我总是无法传递 :id
键。我尝试了几种不同的方法来传递 link 中的变量,但一直出现相同的错误,即缺少 :id
键。当我将 link 替换为要显示 comment.id
的段落时,它会完美显示,因此在我看来它肯定可用。
No route matches {:action=>"show", :controller=>"comments", :format=>nil, :id=>nil, :post_id=>11} missing required keys: [:id]
如您所见,它还尝试调用 "show" 操作,但我敢打赌,只要它正确传递了 id,就会解决这个问题。
知道我在这里可能做错了什么吗?
如您所见,错误是
没有路由匹配 {:action=>"show", :controller=>"comments", :format=>nil, :id=>nil , :post_id=>11}
并且在你的 link_to 中有 comment.id:
<%= link_to "Delete comment", post_comment_path(@post.id, id: comment.id), method: :delete %>
这意味着你正在传递一个没有id的对象(没有保存在数据库中)。您可能正在建立您的评论,这就是他们还没有 ID 的原因。
解决此问题的方法之一是像这样使用您的 link_to:
<%= link_to("Delete comment", post_comment_path(@post, comment), method: :delete) unless comment.new_record? %>
不会显示新记录的 link,因为您不能删除数据库中不存在的内容。
在我的项目中有 2 个嵌套资源:
Rails.application.routes.draw do
resources :posts do
resources :comments
end
root 'posts#index'
end
我正在使用部分 _comment.html.erb
渲染一组评论 <%= render partial: "comments/comment", collection: @post.comments %>
部分看起来像这样
<div class="comment_wrapper">
<p class="comment_name"><%= comment.name %></p>
<p class="comment_date"><%= comment.created_at %></p>
<p class="comment_body"><%= comment.body %></p>
<%= link_to "Delete comment", post_comment_path(@post.id, id: comment.id), method: :delete%>
</div>
问题出在 "Delete comment" link 中的嵌套路由。
我总是无法传递 :id
键。我尝试了几种不同的方法来传递 link 中的变量,但一直出现相同的错误,即缺少 :id
键。当我将 link 替换为要显示 comment.id
的段落时,它会完美显示,因此在我看来它肯定可用。
No route matches {:action=>"show", :controller=>"comments", :format=>nil, :id=>nil, :post_id=>11} missing required keys: [:id]
如您所见,它还尝试调用 "show" 操作,但我敢打赌,只要它正确传递了 id,就会解决这个问题。 知道我在这里可能做错了什么吗?
如您所见,错误是
没有路由匹配 {:action=>"show", :controller=>"comments", :format=>nil, :id=>nil , :post_id=>11}
并且在你的 link_to 中有 comment.id:
<%= link_to "Delete comment", post_comment_path(@post.id, id: comment.id), method: :delete %>
这意味着你正在传递一个没有id的对象(没有保存在数据库中)。您可能正在建立您的评论,这就是他们还没有 ID 的原因。
解决此问题的方法之一是像这样使用您的 link_to:
<%= link_to("Delete comment", post_comment_path(@post, comment), method: :delete) unless comment.new_record? %>
不会显示新记录的 link,因为您不能删除数据库中不存在的内容。