Ruby-on-rails – Overriding named routes provided by Rails 3 Engines

rails-enginesroutesruby-on-railsruby-on-rails-3

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 engine.

From the engine config/routes.rb:

match 'their_named_route' => 'controller#action', :as => 'the_route'

From my application config/routes.rb:

match 'my_named_route' => 'controller#action', :as => 'the_route'

However, when I inspect the routes, both seem to be active (and their route appears to "win", at least within the engine controllers)

$ rake routes
the_route  /my_named_route(.:format)    {:controller=>"controller", :action=>"action"}
the_route  /their_named_route(.:format) {:controller=>"controller", :action=>"action"}

Is there a good way to force my local application's named route to take priority?

Best Answer

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.

Related Topic