我想向我的控制器添加另一个动作,我无法弄清楚如何.
我在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) %>
Run Code Online (Sandbox Code Playgroud)
但它给了我错误:
undefined method `schedule_item_path' for #<#<Class:0x6287b50>:0x62730c0>
Run Code Online (Sandbox Code Playgroud)
不确定我应该从哪里开始.
dee*_*our 49
一种更好的写作方式
resources :items, :collection => {:schedule => :post, :save_scheduling => :put}
Run Code Online (Sandbox Code Playgroud)
是
resources :items do
collection do
post :schedule
put :save_scheduling
end
end
Run Code Online (Sandbox Code Playgroud)
这将创建像这样的URL
/items/schedule/items/save_scheduling因为你传递一个item到您的schedule_...路线的方法,你可能想member的路线,而不是collection路线.
resources :items do
member do
post :schedule
put :save_scheduling
end
end
Run Code Online (Sandbox Code Playgroud)
这将创建像这样的URL
/items/:id/schedule/items/:id/save_scheduling现在可以使用schedule_item_path接受Item实例的路由方法.最后一个问题是,您的link_to目标是生成GET请求,而不是POST您的路线所需的请求.您需要将此:method选项指定为选项.
link_to("Title here", schedule_item_path(item), method: :post, ...)
Run Code Online (Sandbox Code Playgroud)
推荐阅读:http: //api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
| 归档时间: |
|
| 查看次数: |
17557 次 |
| 最近记录: |