如何在Rails 3中向控制器添加自定义操作

我想向我的控制器添加另一个动作,我无法弄清楚如何。

我在RailsCasts和大多数StackOverflow主题上发现了这个:

# routes.rb resources :items, :collection => {:schedule => :post, :save_scheduling => :put} # items_controller.rb ... def schedule end def save_scheduling end # items index view:  

但它给了我错误:

 undefined method `schedule_item_path' for #<#:0x62730c0> 

不确定我应该从哪里开始。

一种更好的写作方式

 resources :items, :collection => {:schedule => :post, :save_scheduling => :put} 

 resources :items do collection do post :schedule put :save_scheduling end end 

这将创建像这样的URL

  • /items/schedule
  • /items/save_scheduling

因为您将item传递到schedule_...路线方法,您可能需要member路线而不是collection路线。

 resources :items do member do post :schedule put :save_scheduling end end 

这将创建像这样的URL

  • /items/:id/schedule
  • /items/:id/save_scheduling

现在可以使用接受Item实例的路由方法schedule_item_path 。 最后一个问题是,你现在的link_to将生成一个GET请求,而不是路由所需的POST请求。 您需要将其指定为:method选项。

 link_to("Title here", schedule_item_path(item), method: :post, ...) 

推荐阅读: http : //api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Rails Routing from the Outside In参考Rails Routing from the Outside In

以下应该工作

 resources :items do collection do post 'schedule' put 'save_scheduling' end end 

你可以写这样的routes.rb

 match "items/schedule" => "items#schedule", :via => :post, :as => :schedule_item match "items/save_scheduling" => "items#save_scheduling", :via => :put, :as => :save_scheduling_item 

并且link_to帮助器不能在Rails 3中发送post动词。

您可以从外部看到Rails路由