Rails:从视图更新嵌套资源

时间:2013-08-12 18:53:04

标签: ruby-on-rails ruby-on-rails-3 forms routes

我需要表单来更新任务,这些任务属于项目视图中的项目并获得错误

No route matches [PATCH] "/projects/1/tasks/1/edit"

这是可用的路线列表

project_tasks_path   GET     /projects/:project_id/tasks(.:format)   tasks#index
                     POST    /projects/:project_id/tasks(.:format)   tasks#create
new_project_task_path    GET     /projects/:project_id/tasks/new(.:format) tasks#new
edit_project_task_path   GET     /projects/:project_id/tasks/:id/edit(.:format)  tasks#edit
project_task_path    GET     /projects/:project_id/tasks/:id(.:format)   tasks#show
                     PATCH   /projects/:project_id/tasks/:id(.:format)   tasks#update
                     PUT     /projects/:project_id/tasks/:id(.:format)   tasks#update
                     DELETE  /projects/:project_id/tasks/:id(.:format)   tasks#destroy
 projects_path   GET     /projects(.:format)     projects#index
                     POST    /projects(.:format)     projects#create
 new_project_path    GET     /projects/new(.:format)     projects#new
 edit_project_path   GET     /projects/:id/edit(.:format)    projects#edit
 project_path    GET     /projects/:id(.:format)     projects#show
                     PATCH   /projects/:id(.:format)     projects#update
                     PUT     /projects/:id(.:format)     projects#update
                     DELETE  /projects/:id(.:format)     projects#destroy
 projects_update_path    POST    /projects/update(.:format)  projects#update
 projects_add_path   POST    /projects/add(.:format)     projects#add
                     POST    /projects/:project_id/tasks/:id/edit(.:format)  tasks#edit
 root_path   GET     /   projects#index

这是视图代码

<% @projects.each do |project| %>

<%= project.name %>
<% project.tasks.each do |task| %>

  <%= task.name %></p>

  <%= form_for [task.project, task], url: edit_project_task_path(task.project, task) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.submit "Update task" %>
  <% end %>
<% end %>
<% end %>

2 个答案:

答案 0 :(得分:0)

您正在尝试将请求提交到edit路由。

相反,请尝试在project_task_path(task.project, task)中使用form_for。 Rails会知道将PATCH请求发送到正确的路由。

答案 1 :(得分:0)

在表单中,您的网址必须为project_task_path(project_id: task.project, task),因为您要使用PUT。这里的错误来自Rails搜索routes.rb的方式。它正在寻找一个PUT edit_project_task_path,但你只有一个GET。