【发布时间】:2026-02-18 17:00:01
【问题描述】:
我发现资源路由方法很方便,但我完全讨厌它没有创建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
编辑。我的“有点复杂的范围”的例子
# 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
【问题讨论】:
-
你能举出更多例子来说明你所使用的复杂范围吗?我认为复杂的范围可能是一种气味,如果您可以简化路由而不是通过寻找
create_xxx助手来解决它,那么值得研究一下
标签: ruby-on-rails rest routes