且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-21 21:43:10

更好的写作方式

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

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

这将创建像

  • /items/schedule
  • /items/save_scheduling

因为您将 item 传递到您的 schedule_... 路由方法中,所以您可能需要 member 路由而不是 集合路由.

Because you're passing an item into your schedule_... route method, you likely want member routes instead of collection routes.

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

这将创建像

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

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

Now a route method schedule_item_path accepting an Item instance will be available. The final issue is, your link_to as it stands is going to generate a GET request, not a POST request as your route requires. You need to specify this as a :method option.

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

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