为什么我的嵌套资源中“没有路由匹配[POST]”?

时间:2011-07-26 00:05:21

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

我有一个包含projects todos tasksNo route matches [POST] "/projects/1/todos/19/tasks/new" 的项目。当我尝试创建新任务时,我在提交时收到此错误:

<%= form_for [@todo, @todo.tasks.new], :url => new_project_todo_task_path(@project, @todo) do |f| %>

        <div class="field">
          <%= f.label :description, "Description" %><br />
          <%= f.text_area :description %>
        </div>
        <div class="actions">
          <%= f.submit %> or <%= link_to "Cancel", "#", :id => "cancel_new_task_link" %>
        </div>  

    <% end %>

这是我的表格:

class TasksController < ApplicationController
  before_filter :authenticated?
  before_filter :get_project_and_todo

  respond_to :html, :xml, :json, :js

  def new
    @task = @todo.tasks.new
  end

  def create
    @task = @todo.tasks.new(params[:task])
    if @task.save
      respond_with @todo, :location => project_todo_path(@project, @todo)
    else
      render "new"
    end
  end

  private

  def get_project_and_todo
    @project = Project.find(params[:project_id])
    @todo = @project.todos.find(params[:todo_id])
  end


end

这是我的控制器:

resources :projects do
    resources :todos do
        resources :tasks
    end
end

以下是我的路线:

{{1}}

由于

1 个答案:

答案 0 :(得分:4)

您的网址不应为new_project_todo_task_path(@project, @todo)。您不需要在此处指定URL,因为Rails将从传递给form_for的参数中暗示它。

如果最终对象是新对象而未在数据库中保留,那么它将发出POST请求,在本例中为/projects/:project_id/todos。您在示例中声明要向POST发出/projects/:project_id/todos/new请求,但没有POST路由,这就是失败的原因。