Ruby on Rails 作用域
示例
Rails提供了几种组织路线的方法。
URL范围:
scope 'admin' do get 'dashboard', to: 'administration#dashboard' resources 'employees' end
这将产生以下路线
get '/admin/dashboard', to: 'administration#dashboard' post '/admin/employees', to: 'employees#create' get '/admin/employees/new', to: 'employees#new' get '/admin/employees/:id/edit', to: 'employees#edit' get '/admin/employees/:id', to: 'employees#show' patch/put '/admin/employees/:id', to: 'employees#update' delete '/admin/employees/:id', to: 'employees#destroy'
在服务器端,将某些视图保留在不同的子文件夹中,以将管理视图与用户视图分开可能更有意义。
按模块范围
scope module: :admin do get 'dashboard', to: 'administration#dashboard' end
module在给定名称的子文件夹下查找控制器文件
get '/dashboard', to: 'admin/administration#dashboard'
您可以通过添加as参数来重命名路径助手前缀
scope 'admin', as: :administration do get 'dashboard' end # => administration_dashboard_path
Rails提供了使用该namespace方法完成上述所有操作的便捷方法。以下声明是等效的
namespace :admin do end scope 'admin', module: :admin, as: :admin
控制器范围
scope controller: :management do get 'dashboard' get 'performance' end
这会产生这些路线
get '/dashboard', to: 'management#dashboard' get '/performance', to: 'management#performance'
浅层嵌套
资源路由接受一个:shallow选项,可以在可能的情况下帮助缩短URL。资源不应嵌套超过一层。避免这种情况的一种方法是创建浅路径。目标是在不需要它们的地方删除父集合URL段。最终结果是生成唯一嵌套航线的:index,:create和:new动作。其余的保留在它们自己的浅URL上下文中。自定义浅层路由的作用域有两种选择:
:shallow_path:使用指定参数为成员路径添加前缀
scopeshallow_path:"sekret"do
resources:articlesdo
resources:comments,shallow:true
end
end
:shallow_prefix:将指定参数添加到命名助手
scopeshallow_prefix:"sekret"do
resources:articlesdo
resources:comments,shallow:true
end
end
我们还可以shallow通过以下方式进一步说明路线:
resources :auctions, shallow: true do resources :bids do resources :comments end end
或者编码如下(如果您很满意):
resources :auctions do shallow do resources :bids do resources :comments end end end
产生的路线为:
如果仔细分析生成的路由,您会注意到URL的嵌套部分仅在需要确定要显示的数据时才包括在内。