I'm using Rails 4.2 with Rails Engine to handle my admin panel. I want to move the engine code to the main rails app and part of doing that is moving the routes.
For now, my routes in the Engine my-web-app/lib/admin/config/routes.rb
is something like:
Admin::Engine.routes.draw do
resources :countries, only: [:index]
end
And at my app's routes config/routes.rb
:
Rails.application.routes.draw do
.. some routes ...
mount GlobalAdmin::Engine => "/admin"
end
Now the engine's route for countries is countries_url
NOT admin_countries_url
but for URL you'll need to access it with something like admin/countries
(this is the default behavior for the engine and I want to keep it this way).
What I did is that I moved my-web-app/lib/admin/config/routes.rb
to my-web-app//config/routes.admin.rb
and made it look something like:
Rails.application.routes.draw do
resources :countries, only: [:index]
end
And then in my config/application.rb
I added something like this:
config.paths["config/routes.rb"] = [
Rails.root.join("config/routes.admin.rb"),
Rails.root.join("config/routes.rb")
]
The problem with this approach is that I have countries_url
, however, I can't access it with admin namespace URL like admin/countries
. If I add namespace admin
something like:
Rails.application.routes.draw do
namespace :admin do
resources :countries, only: [:index]
end
end
Then I'll need to refer to countries url with admin_countries_url
which is not the behavior I need.
Any help of how to move the routes from the engine without affecting the previous engine routes?
I'm aware that routes inside an engine are isolated from the application by default. The application and its engines can have routes with the same names, so integrating both can cause some issues, however I want to preserve the exact routes if possible and not to add a namespace and stick with the exact routes names.
Use scope
instead of namespace
:
Rails.application.routes.draw do
scope path: "/admin" do
resources :countries
end
end
max@MaxBook ~/p/sandbox> rails routes
Prefix Verb URI Pattern Controller#Action
countries GET /admin/countries(.:format) countries#index
POST /admin/countries(.:format) countries#create
new_country GET /admin/countries/new(.:format) countries#new
edit_country GET /admin/countries/:id/edit(.:format) countries#edit
country GET /admin/countries/:id(.:format) countries#show
PATCH /admin/countries/:id(.:format) countries#update
PUT /admin/countries/:id(.:format) countries#update
DELETE /admin/countries/:id(.:format) countries#destroy
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.