Ruby-on-Rail 3路由的作用域和命名空间之间的差异

我不能理解命名空间和作用域在 ruby-on-ails 3的路由中有什么区别。

有人能解释一下吗?

namespace "admin" do
resources :posts, :comments
end


scope :module => "admin" do
resources :posts, :comments
end
37542 次浏览

The difference lies in the paths generated.

命名空间的路径是 admin_posts_pathadmin_comments_path,而作用域的路径只是 posts_pathcomments_path

通过将 :name_prefix选项传递到范围,可以得到与命名空间相同的结果。

例子总是对我有帮助,所以这里有一个例子:

namespace :blog do
resources :contexts
end

会给我们以下的路线:

    blog_contexts GET    /blog/contexts(.:format)          {:action=>"index", :controller=>"blog/contexts"}
POST   /blog/contexts(.:format)          {:action=>"create", :controller=>"blog/contexts"}
new_blog_context GET    /blog/contexts/new(.:format)      {:action=>"new", :controller=>"blog/contexts"}
edit_blog_context GET    /blog/contexts/:id/edit(.:format) {:action=>"edit", :controller=>"blog/contexts"}
blog_context GET    /blog/contexts/:id(.:format)      {:action=>"show", :controller=>"blog/contexts"}
PUT    /blog/contexts/:id(.:format)      {:action=>"update", :controller=>"blog/contexts"}
DELETE /blog/contexts/:id(.:format)      {:action=>"destroy", :controller=>"blog/contexts"}

Using scope...

scope :module => 'blog' do
resources :contexts
end

Will give us:

     contexts GET    /contexts(.:format)           {:action=>"index", :controller=>"blog/contexts"}
POST   /contexts(.:format)           {:action=>"create", :controller=>"blog/contexts"}
new_context GET    /contexts/new(.:format)       {:action=>"new", :controller=>"blog/contexts"}
edit_context GET    /contexts/:id/edit(.:format)  {:action=>"edit", :controller=>"blog/contexts"}
context GET    /contexts/:id(.:format)       {:action=>"show", :controller=>"blog/contexts"}
PUT    /contexts/:id(.:format)       {:action=>"update", :controller=>"blog/contexts"}
DELETE /contexts/:id(.:format)       {:action=>"destroy", :controller=>"blog/contexts"}

这里有一些关于这个主题的好的阅读材料: http://edgeguides.rubyonrails.org/routing.html#controller-namespaces-and-routing

导轨

“命名空间范围将自动添加 :as以及 :module:path前缀。”

所以

namespace "admin" do
resources :contexts
end

scope "/admin", as: "admin", module: "admin" do
resources :contexts
end

范围命名空间都在确定指向给定默认选项的一组路由的范围。
除了对于 范围命名空间没有默认选项 :path, :as, :module, :shallow_path and :shallow_prefix options all default to the name of the namespace.

范围命名空间的可用选项 对应于 火柴的选项。

scope is bit complex, but provides more options to fine-tune exactly what you want to do.

Scope 支持三个 选项: 模块、路径和作为

换句话说,由

namespace :admin do
resources :posts
end

是一样的

scope module: 'admin', path: 'admin', as: 'admin' do
resources :posts
end

In other words, we can say that there are no default options for 范围 as compared to namespace. 命名空间 add all these options by default. Thus using scope, we can more fine tune the routes as required.

如果深入研究 范围命名空间的默认行为,您会发现 范围在默认情况下只支持 翻译: path选项,而 命名空间在默认情况下支持三个选项 模块、路径和作为

更多信息,请参考文件 名称空间和路由