Named routes in mounted rails engine

前端 未结 3 1008
青春惊慌失措
青春惊慌失措 2020-12-24 12:12

I\'m making a small rails engine which I mount like this:

mount BasicApp::Engine => \"/app\"

Using this answer I have verified that all

3条回答
  •  孤独总比滥情好
    2020-12-24 12:43

    On Rails 4 the engine_name directive did not work for me.
    To access a named route defined in engine's routes from engine's own view or controller, I ended up using the verbose

    BasicApp::Engine.routes.url_helpers.new_post_path
    

    I recommend defining a simple helper method to make this more usable

    # in /helpers/basic_app/application_helper.rb
    
    module BasicApp::ApplicationHelper
      def basic_app_engine
        @@basic_app_engine_url_helpers ||= BasicApp::Engine.routes.url_helpers
      end
    end
    

    With this in place you can now use

    basic_app_engine.new_post_path
    

    In case you need to access your main application helper from the engine you can just use main_app:

    main_app.root_path
    

提交回复
热议问题