ruby-on-rails 3路由的范围和命名空间之间的差异

nev*_*ame 106 ruby-on-rails

我无法理解ruby-on-rails 3路由中命名空间和范围之间的区别.

有人可以解释一下吗?

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

scope :module => "admin" do
  resources :posts, :comments
end
Run Code Online (Sandbox Code Playgroud)

alt*_*ive 103

不同之处在于生成的路径.

路径是admin_posts_pathadmin_comments_path命名空间的路径,而它们只是posts_pathcomments_path范围.

通过将:name_prefix选项传递给作用域,可以获得与命名空间相同的结果.

  • 为了更好地理解差异:考虑使用范围通过URL和命名空间进行本地化以进行嵌套,例如url:http://domain.com/nl/admin/panel.nl是范围,admin是命名空间. (29认同)
  • 它将路径路径使用的实际路径更改为"/ admin/whatever",就像命名空间一样.唯一不同的是添加到辅助方法的前缀. (2认同)

ynk*_*nkr 66

示例总是帮助我,所以这是一个例子:

namespace :blog do
  resources :contexts
end
Run Code Online (Sandbox Code Playgroud)

会给我们以下路线:

    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"}
Run Code Online (Sandbox Code Playgroud)

使用范围......

scope :module => 'blog' do
  resources :contexts
end
Run Code Online (Sandbox Code Playgroud)

会给我们:

     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"}
Run Code Online (Sandbox Code Playgroud)

以下是关于这个主题的一些很好的解读:http://edgeguides.rubyonrails.org/routing.html#controller-namespaces-and-routing


mon*_*ike 53

导轨指南

"该命名空间范围会自动添加:as,以及:module:path前缀."

所以

namespace "admin" do
  resources :contexts
end
Run Code Online (Sandbox Code Playgroud)

是相同的

scope "/admin", as: "admin", module: "admin" do
  resources :contexts
end
Run Code Online (Sandbox Code Playgroud)