Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 form_for nested routes for custom action

My setup: Rails 3.0.9, Ruby 1.9.2

I added a custom action to a nested resource task.

routes.rb
resources :tasks
resources :projects do
  resources :tasks, :constraints => { :protocol => "http" } do 
    put :cancel, :on => :member
  end 
end

rake routes shows

cancel_project_task PUT /projects/:task_id/tasks/:id/cancel(.:format) {:protocol=>"http", :action=>"cancel", :controller=>"tasks"}

In my controller,

tasks_controller.rb  
  def cancel
    @task = Task.find(params[:id])

    respond_to do |format|
      if @task.cancel
        format.html { redirect_to(@task, :notice => 'Task was successfully canceled.') }
      else
        format.html { render :action => "edit" }
      end
    end
  end

I need to define a form to perform the action, here's what I have currently

_form.html.erb for subscription
  <%= form_for [@project, @task], :url => { :action => 'cancel' } do |f| %>
    <%= f.submit "Cancel your task"%> 
  <% end %>

It throws an error

No route matches {:action=>"cancel", :controller=>"tasks"}

I also tried adding :method => "put" with the same error

_form.html.erb for subscription
  <%= form_for [@project, @task], :url => { :action => 'cancel', :method => "put" } do |f| %>
    <%= f.submit "Cancel your task"%> 
  <% end %>

Anyone knows the correct form_format syntax to accomplish this?

like image 945
Bob Avatar asked Aug 12 '11 21:08

Bob


1 Answers

In case anyone wants the answer, here's what I had to do

<%= form_for [@project, @task], :url => cancel_project_task_path(@project, @task) do |f| %>

It took me way too long to figure this out, hopefully this helps the next unsuspecting developer.

like image 66
Bob Avatar answered Sep 19 '22 10:09

Bob