简体   繁体   中英

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'.

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

 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?

 <% @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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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