Rails delete link nested routes

假如想象 提交于 2019-12-12 05:03:37

问题


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


回答1:


Please try this:

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

and let me know




回答2:


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>


来源:https://stackoverflow.com/questions/16236414/rails-delete-link-nested-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!