cbmeeks
cbmeeks

Reputation: 11410

Why am I getting "no route matches [POST]" in my nested resources?

I have a project that contains projects that have todos that have tasks. When I try to create a new task, I get this error when I submit:

No route matches [POST] "/projects/1/todos/19/tasks/new"

Here is my form:

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

Here is my controller:

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

Here are my routes:

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

Thanks

Upvotes: 2

Views: 6938

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107718

Your URL should not be new_project_todo_task_path(@project, @todo). You don't need to specify the URL here as Rails will imply it from the parameters passed in to form_for.

If the final object is a new object and not persisted in the database then it will make a POST request to, in this case, /projects/:project_id/todos. You're declaring in your example that you want to make a POST request to /projects/:project_id/todos/new, for which there is no POST route and that is why it's failing.

Upvotes: 4

Related Questions