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

9

我的设置: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个回答

23

如果有人想知道答案,这是我所做的

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

我花了太长时间来弄清楚这个问题,希望这能帮助下一个不知情的开发者。


谢谢,我浪费了几个小时尝试使用“url: {action: my_action}”。 - constantine1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接