如何在 Rails 3 中向控制器添加自定义操作 [英] How to add a custom action to the controller in Rails 3
问题描述
我想向控制器添加另一个操作,但不知道如何操作.
I want to add another action to my controller, and I can't figure out how.
我在 RailsCasts 和大多数 StackOverflow 主题上找到了这个:
I found this on RailsCasts, and on most StackOverflow topics:
# 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) %>
但它给了我错误:
undefined method `schedule_item_path' for #<#<Class:0x6287b50>:0x62730c0>
不知道我应该从哪里开始.
Not sure where I should go from here.
推荐答案
更好的写作方式
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
这篇关于如何在 Rails 3 中向控制器添加自定义操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!