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:使用指定参数为成员路径添加前缀

    scope shallow_path: "sekret" do
     resources :articles do
       resources :comments, shallow: true
     end
    end
  • :shallow_prefix:将指定参数添加到命名助手

    scope shallow_prefix: "sekret" do
     resources :articles do
       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

产生的路线为:

字首动词URI模式
bid_comments得到/bids/:bid_id/comments(.:format)

开机自检/bids/:bid_id/comments(.:format)
new_bid_comment得到/bids/:bid_id/comments/new(.:format)
edit_comment得到/comments/:id/edit(.:format)
评论得到/comments/:id(.:format)

补丁/comments/:id(.:format)

/comments/:id(.:format)

删除/comments/:id(.:format)
拍卖价得到/auctions/:auction_id/bids(.:format)

开机自检/auctions/:auction_id/bids(.:format)
new_auction_bid得到/auctions/:auction_id/bids/new(.:format)
edit_bid得到/bids/:id/edit(.:format)
出价得到/bids/:id(.:format)

补丁/bids/:id(.:format)

/bids/:id(.:format)

删除/bids/:id(.:format)
拍卖会得到/auctions(.:format)

开机自检/auctions(.:format)
new_auction得到/auctions/new(.:format)
edit_auction得到/auctions/:id/edit(.:format)
拍卖得到/auctions/:id(.:format)

补丁/auctions/:id(.:format)

/auctions/:id(.:format)

删除/auctions/:id(.:format)

如果仔细分析生成的路由,您会注意到URL的嵌套部分仅在需要确定要显示的数据时才包括在内。