ruby-on-rails 3のルーティングにおける名前空間とスコープの違いが理解できません。
誰かが説明してもらえますか?
namespace "admin" do
resources :posts, :comments
end
scope :module => "admin" do
resources :posts, :comments
end
ruby-on-rails 3のルーティングにおける名前空間とスコープの違いが理解できません。
誰かが説明してもらえますか?
namespace "admin" do
resources :posts, :comments
end
scope :module => "admin" do
resources :posts, :comments
end
回答:
違いは、生成されるパスにあります。
パスがあるadmin_posts_path
とadmin_comments_path
、彼らはただであるが、名前空間のposts_path
とcomments_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"}
スコープを使用しています...
scope :module => 'blog' do
resources :contexts
end
私たちに与えるでしょう:
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
および:shallow_prefix
名前空間の名前のオプションすべてのデフォルト。
スコープと名前空間の両方で使用可能なオプションは、matchのオプションに対応しています。
スコープは少し複雑ですが、やりたいことを正確に微調整するためのオプションが増えます。
スコープは、モジュール、パス、およびasの 3つのオプションをサポートします。すべてのitオプションでスコープが表示される場合、それは名前空間とまったく同じです。
つまり、によって生成されたルート
namespace :admin do
resources :posts
end
と同じ
scope module: 'admin', path: 'admin', as: 'admin' do
resources :posts
end
つまり、名前空間と比較して、スコープにはデフォルトのオプションがないと言えます。名前空間は、デフォルトでこれらすべてのオプションを追加します。したがって、スコープを使用して、必要に応じてルートをさらに微調整できます。
あなたがに深く見てみる場合はスコープと名前空間のデフォルトの動作は、その見つける範囲をのみ、デフォルト支持体によってパス:オプションとして、名前空間のサポートの3つのオプションのモジュール、パスととして、デフォルトで。
詳細については、ドキュメントの名前空間とルーティングを参照してください。