简体   繁体   English

Rails删除链接嵌套路线

[英]Rails delete link nested routes

I'm writing a simple todo app which has projects and projects has many tasks. 我正在编写一个简单的待办应用程序,其中包含项目,并且项目有很多任务。 I want to be able to delete a task within a project. 我希望能够删除项目中的任务。 But when I try to link_to a delete method I get undefined method 'task_path'. 但是,当我尝试将link_to到delete方法时,会得到未定义的方法'task_path'。

view code 查看代码

<ul>
  <% @project.tasks.each do |task| %>
    <li><%= task.name %></li> <%= link_to "delete", task, :method  => :delete %></br>
  <% end %>
</ul>

tasks controller 任务控制器

  def destroy
    @project = Project.find(params[:project_id])
    @task = @project.tasks.find(params[:id])
    @task.destroy
    redirect_to @project, :notice => "Task Deleted"
  end

routes.rb routes.rb

 resources :projects do
    resources :tasks
  end

Update: So I have delete working. 更新:所以我有删除工作。 But now as I'm iterating through each task, there's an extra delete link which routes to http://todoapp.dev/projects/9/tasks and gives No route matches [DELETE] "/projects/9/tasks" Why is the extra delete link in there? 但是现在当我遍历每个任务时,有一个额外的删除链接,该链接会路由到http://todoapp.dev/projects/9/tasks,并且没有路由匹配[DELETE]“ / projects / 9 / tasks”为什么那里的多余删除链接?

 <% @project.tasks.each do |task| %>
    <%= task.name %> <%= link_to "delete", [@project, task], :method  => :delete %>
  <% end %>

在此处输入图片说明

在此处输入图片说明

Please try this: 请尝试以下方法:

<%= link_to "delete", [@project, task], :method  => :delete %>

and let me know 让我知道

Running rake routes you will see that the delete is mapped to project_task. 运行rake routes您将看到删除映射到project_task。

You may use 您可以使用

<ul>
  <% @project.tasks.each do |task| %>
    <li><%= task.name %></li> <%= link_to "delete", project_task_path(@project, task), :method  => :delete %></br>
  <% end %>
</ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM