【问题标题】:Rails: Fail to pass multiple variable-ids to nested routeRails:无法将多个变量 ID 传递给嵌套路由
【发布时间】:2015-10-25 12:52:22
【问题描述】:

在我的项目中有 2 个嵌套资源:

Rails.application.routes.draw do
resources :posts do
    resources :comments 
end
root 'posts#index'
end

我正在使用部分 _comment.html.erb 渲染一组 cmets

    <%= 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>

问题在于“删除评论”链接中的嵌套路由。 我一直无法传递:id 密钥。我尝试了几种不同的方法来传递链接中的变量,但不断收到相同的错误,即缺少 :id 键。当我用段落替换链接以显示comment.id 时,它会完美显示,因此在我看来它绝对可用。

No route matches {:action=>"show", :controller=>"comments", :format=>nil, :id=>nil, :post_id=>11} missing required keys: [:id]

如您所见,它还尝试调用“显示”操作,但我敢打赌,只要它正确传递了 id,就会解决这个问题。 有什么想法我可能在这里做错了吗?

【问题讨论】:

    标签: ruby-on-rails routes nested


    【解决方案1】:

    如你所见,错误是

    没有路由匹配 {:action=>"show", :controller=>"cmets", :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 的对象(未保存在数据库中)。您可能正在构建您的 cmets,这就是他们还没有 id 的原因。

    解决此问题的方法之一是像这样使用您的 link_to:

    <%= link_to("Delete comment", post_comment_path(@post, comment), method: :delete) unless comment.new_record? %>
    

    其中不会显示新记录的链接,因为您无法删除数据库中尚不存在的内容。

    【讨论】:

    • 嘿哇谢谢,我自己永远也想不通!在我的 PostController 的 show 操作中,我确实定义了一个新注释,这样我就可以在 show.html.erb 的底部创建一个用于创建 cmets 的表单。但当然,该评论尚未保存。再次感谢 Gen!
    • @sjbuysse,当然,事情。我想每个人都以同样的方式了解了这个错误。如果对您有用,请接受答案。谢谢。
    猜你喜欢
    • 2014-10-05
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多