Named routes in mounted rails engine

前端 未结 3 1005
青春惊慌失措
青春惊慌失措 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:48

    The right way

    I believe the best solution is to call new_post_path on the Engine's routes proxy, which is available as a helper method. In your case, the helper method will default to basic_app_engine, so you can call basic_app_engine.new_post_path in your views or helpers.

    If you want, you can set the name in one of two ways.

    # in engine/lib/basic_app/engine.rb:
    module BasicApp
      class Engine < ::Rails::Engine
        engine_name 'basic'
      end
    end
    

    or

    # in app/config/routes.rb:
    mount BasicApp::Engine => '/app', :as => 'basic'
    

    In either case, you could then call basic.new_posts_path in your views or helpers.

    Another way

    Another option is to not use a mounted engine and instead have the engine add the routes directly to the app. Thoughtbot's HighVoltage does this. I don't love this solution because it is likely to cause namespace conflicts when you add many engines, but it does work.

    # in engine/config/routes.rb
    Rails.application.routes.draw do
      resources :posts, :path => '' do
                    resources :post_comments
                    resources :post_images
      end
    end
    
    # in app/config/routes.rb:
    # (no mention of the engine)
    

提交回复
热议问题