Engine routes in Application Controller

前端 未结 5 2147
予麋鹿
予麋鹿 2020-12-29 10:20

I have a before_filter hook in my main app\'s application controller that does something like: (It doesn\'t just put a link in the flash, there is a message, but it isn\'t r

5条回答
  •  不知归路
    2020-12-29 11:06

    You can keep the isolate_namespace, as strongly recommended by Rails Engine guide, and do this:

    # inside your main_app's config/routes.rb
    Rails.application.routes.draw do
      root to: 'home#index'
    
      mount MyEngine::Engine, at: "/" 
    end
    
    # inside your engine's controller
    module MyEngine
      class SomeController << ::ApplicationController
        # include main_app's route helpers
        helper Rails.application.routes.url_helpers
    
      end
    end
    

    And inside your gem, make sure all the url helpers are prefixed with the correct routing proxy method (e.g. my_engine.pages_path).

    Your main_app's layout and engine's controller will route and link to those url helpers correctly to the main app. You don't have to add "main_app" prefix anywhere to the main app. The only downside is you're mounting your engine's routes at main_app's root path, which could collide with any routes by the same name. This is expected anyway if you were to do non-isolate_namespace.

提交回复
热议问题