不要使用Rails引擎名称为路由添加前缀

时间:2014-07-11 00:57:49

标签: ruby-on-rails ruby ruby-on-rails-3 rails-engines

我正在转换应用程序以使用Rails引擎。我的引擎位于engines/web文件夹中。在config/routes.rb我按照这样安装:

mount Web::Engine => '/', as: 'web_engine'

文件夹结构如下:

config
  routes.rb
engines
  web
    config
      routes.rb
    app
      controllers
        web 
          application_controller.rb
          ...
    lib
      ...

引擎定义如下:

module Web
  class Engine < Rails::Engine
    isolate_namespace Web
  end
end

我在Web引擎中的应用程序控制器定义如下:

module Web
  class ApplicationController < ::ActionController::Base
    layout 'web/layouts/application'

    # other code
  end
end

问题在于Web::ApplicationController内部我必须将路由称为web_engine.my_route_path而不是my_route_path。有没有办法从Web引擎内部访问没有web_engine前缀的路由?

3 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

module Web
  class Engine < Rails::Engine
    isolate_namespace Web
  end
end

有关路线的详细信息,请参阅docs。另请查看Engine.isolate_namespace说明。

答案 1 :(得分:0)

将您的url帮助器包括在引擎控制器中:

module Web
  class ApplicationController < ::ActionController::Base
    helper Web::Enginer.routes.url_helpers

  end
end

答案 2 :(得分:-1)

你必须

1-从您的_engine_path_ / lib / web / engine.rb文件中删除行isolated_namespace(我假设您知道对象命名冲突风险的后果)

2-从_app_path_ / config / route.rb文件中删除行mount Web::Engine ...

3-在Rails.application.routes.draw区块中定义引擎中的路线。所以你的_engine_path_ / config / routes.rb看起来像:

Rails.application.routes.draw do
  resources :things
  get 'my_path', to: 'my_controller#my_action'
end

然后,引擎中定义的路线不会以引擎名称为前缀

您可以通过应用中的引擎访问路线助手,反之亦然,无前缀且无需确定引擎名称