How to have one resource in routes for namespace and root path altogether - Rails 4

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

I am making a custom admin panel in a namespace "admin".

I have resources "courses" within that namespace.

But I would also like a route to "courses" that is not in that namespace:

eg: BOTH localhost:3000/admin/courses AND localhost:3000/courses

It's OK if this requires different controllers.

My concern is that its not really DRY if i have both resources for the same route.

namespace admin do    resources :courses end 

and just

resources :courses 

Is there a way to have one resource be shared between namespace and without namespace, or is the example above the way to go?

回答1:

Oh wait ! There's also the possibility to use concerns !

concern :shared_actions do    resources :courses    resources :something_else end   namespace :admin do    concerns :shared_actions end concerns :shared_actions # Will add it to the root namespace ^^ 

EDIT : apparently this is what this guy also tried to do :D



回答2:

I'm not really sure I understand what you mean, but

namespace :something is actually a shorthand for scope :something, module: :something, as: :something

  • scope :something will add /something/ as a URL prefix
  • scope module: :something will add /something as a controller prefix (controllers will be fetched under controlelrs/something/the_controller.rb
  • scope as: :something will add the something as a prefix for path helpers

Now it's totally fine to have both in your routes

resources :courses # Will generate "/courses/", "/courses/new", "/courses/1/edit", ... # And will point to `controllers/courses_controller.rb`  namespace :admin do   resources :courses end # Will generate "/admin/courses/", "/admin/courses/new", "/admin/courses/1/edit", ... # And will point to `controllers/admin/courses_controller.rb` 

Does this answer your question ?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!