无法删除属于另一个资源的资源

unable to delete a resource which belongs to another resource

我的资源是这样组织的:

 resources :tickets do
    resources :comments
 end

当我尝试使用这样的 link 从工单中删除评论时(它们都已列出):

<table class="table">
        <% @ticket.comments.each do |c| %>
            </tr>
                <td><%= c.text %> | <%= link_to "Delete", ticket_comment_path(c), method: :delete, data: {confirm: "Are you sure?"} %></td>
            </tr>
        <% end %>
    </table>

我有一个错误: 没有路由匹配 {:action=>"show", :controller=>"comments", :id=>"5"} 缺少必需的键:[:ticket_id]

正如我所想的那样,ticket_comment_path(c) id 应该是评论的 id 并且 ticket_id 应该被填充。

但不知何故我的 :id 是票证 ID,而 :ticket_id 是空的...

尝试 ticket_comment_path(@ticket, c) - 嵌套资源需要两个 ID 才能正确路由。您可以通过 运行 rake routes | grep comment 查看路线,您会看到类似 DELETE /tickets/:ticket_id/comments/:id

的内容

当您使用嵌套资源时,url 将如下所示

/tickets/:ticket_id/comments/:id

因此,要删除评论,您需要传递 ticker_idcomment_id 两个参数。您的删除 link_to 应如下所示

<%= link_to "Delete", ticket_comment_path(@ticket.id, c), method: :delete, data: {confirm: "Are you sure?"} %>

来源:http://guides.rubyonrails.org/routing.html#nested-resources