Overriding named routes provided by Rails 3 Engines

后端 未结 6 1625
一个人的身影
一个人的身影 2021-01-04 21:58

I am working on a Ruby on Rails 3(.0) application that uses a Rails engine. However, in my local application, I want to override one of the routes provided by the Rails engi

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-04 22:29

    I got around this by moving my engine's routes from config/routes.rb to a class method in the engine class itself:

    module MyEngine
      class Engine < Rails::Engine
        def self.routes
          MyRailsApp::Application.routes.draw do
            resources :products
          end
        end
      end
    end
    

    and then in the base app's routes file:

    MyRailsApp::Application.routes.draw do
      # Routes for base app including the ones overriding MyEngine::Engine.
    
      MyEngine::Engine.routes
    end
    

    I can then happily override any routes in the base app with those in the engine.

    Note that the overriding routes need to be defined before the overridden routes since the earlier defined routes take precedence over later ones.

提交回复
热议问题