我发现资源路由方法非常方便,但我完全不喜欢它不会创建create
和destroy
路径助手。
我明白写作
<% form_for(@object) %>
应该自动获取路由名称,并且我们可以使用数组或符号来自动获取存在时的命名空间/前缀,但是我有许多路由具有复杂的scope
定义,并且不能让create_xxx
帮助者完全惹恼我
没有比写作更简单的解决方案吗? (我正在尝试在生成帮助程序时保留默认的RESTful URL)
complicated_scope do
resources :my_resources, except: [:create, :destroy] do
post '', on: :collection, action: :create, as: 'create' # plus this generates a pluralized version, not very intuitive `create_complicated_scope_my_resourceS_path`
delete '', on: :member, action: :destroy, as: 'destroy'
end
end
EDIT。我的“范围有些复杂”的例子
# Company access routes under /company/
namespace :company do
# I need a company id for all nested controllers (this is NOT a resource strictly speaking, and using resources :companies, only: [] with 'on: :collection' doesn't generate appropriate urls)
scope ':company_id' do
# Company administrators
namespace :admin do
# There is a lot of stuff they can do, not just administration
namespace :administration do
# There are several parameters grouped in different controllers
resources :some_administrations do
... # finally RESTful actions and others here
end
end
end
end
end
答案 0 :(得分:1)
资源路由确实会创建create
和destroy
帮助程序,但是它们的HTTP请求类型(分别是POST和DELETE)会隐含它们,因此路由帮助程序方法应该可以正常工作您提供的代码。
假设您有以下路线定义:
complicated_scope do
resources :my_resources
end
end
作为一个简单的例子,在删除的情况下,您可以使用如下命名路由:
link_to "Delete [resource]", complicated_scope_resource_path(id: @my_resource.id), method: :delete
由于HTTP谓词消除了控制器操作的歧义,因此这个辅助方法路由到控制器的destroy方法。
或者,您也应该能够使用数组语法。
link_to "Delete [resource]", [:complicated_scope, @my_resource], method: :delete
形式也是如此:
<%= form_for [:complicated_scope, @my_resource] do |f| %>
如果@my_resource
是新对象(未保留),就像new
操作一样,这相当于向/ complex_scope / my_resource发送post
请求在请求的正文中形成参数。
或者如果存在@my_resource
,例如edit
操作,则上述内容相当于发送PUT/PATCH
,该update
将路由到/complicated_scope/my_resource/:id/update
你的控制器有{{1}}。