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

Ruby on rails 如何在Rails 3中向控制器添加自定义操作,ruby-on-rails,Ruby On Rails,我想向控制器添加另一个操作,但我不知道如何添加 我在RailsCasts和大多数StackOverflow主题上发现了这一点: # routes.rb resources :items, :collection => {:schedule => :post, :save_scheduling => :put} # items_controller.rb ... def schedule end def save_scheduling end # ite

我想向控制器添加另一个操作,但我不知道如何添加

我在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:
<%= link_to 'Schedule', schedule_item_path(item) %>
#routes.rb
资源:items,:collection=>{:schedule=>:post,:save\u scheduling=>:put}
#项目\u controller.rb
...
def时间表
结束
def save_调度
结束
#项目索引视图:
但它给了我一个错误:

undefined method `schedule_item_path' for #<#<Class:0x6287b50>:0x62730c0>
未定义的方法'schedule\u item\u path'#
不确定我应该从这里走到哪里。

Ref

以下几点应该行得通

resources :items do
  collection do
    post 'schedule'
    put 'save_scheduling'
  end
end
更好的写作方式

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

这将创建如下URL

  • /items/schedule
  • /items/save\u调度
因为您正在将
项目
传递到
计划
路由方法中,所以您可能需要
成员
路由,而不是
集合
路由

resources :items do
  member do
    post :schedule
    put :save_scheduling
  end
end
这将创建如下URL

  • /items/:id/schedule
  • /items/:id/save\u调度
现在,一个路由方法
schedule\u item\u path
接受一个
item
实例将可用。最后一个问题是,您当前的
链接将生成
GET
请求,而不是路线所需的
POST
请求。您需要将其指定为
:方法
选项

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

推荐阅读:

您可以这样编写
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
在Rails 3中,指向
助手的
链接不能发送
post
动词


您可以看到

过于冗长,而且更难维护。是否有其他方法来生成特定的
\u路径
方法?这就是为什么我认为OP应该有
成员
集合,正如我在回答中所概述的。为了让链接工作,我必须这样做:
注意
方法::post
计划项目路径()之外。
是的,小的打字错误。固定的。
match "items/schedule" => "items#schedule", :via => :post, :as => :schedule_item
match "items/save_scheduling" => "items#save_scheduling", :via => :put, :as => :save_scheduling_item