Rails 3 form_for自定义操作的嵌套路由

时间:2011-08-12 21:24:41

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

我的设置:Rails 3.0.9,Ruby 1.9.2

我在嵌套资源任务中添加了自定义操作。

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

rake routes显示

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

在我的控制器中,

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

我需要定义一个表单来执行操作,这是我目前的

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

它会抛出错误

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

我也尝试使用相同的错误添加:method => "put"

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

任何人都知道正确的form_format语法来实现这个目标吗?

1 个答案:

答案 0 :(得分:23)

如果有人想要答案,这就是我必须做的事情

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

我花了太长时间才弄清楚这一点,希望这有助于下一个毫无戒心的开发人员。