不使用Rails Engine名称添加路由前缀

问题描述 投票:5回答:3

我正在转换一个应用程序以使用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前缀的路由?

ruby-on-rails ruby ruby-on-rails-3 rails-engines
3个回答
0
投票

这应该可以解决问题:

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

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


0
投票

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

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

  end
end

-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

那么,您在引擎中定义的路线将不会以引擎名称作为前缀

并且您将可以从应用程序中的引擎访问路由助手,反之亦然,没有前缀,也没有范围内的引擎名称

© www.soinside.com 2019 - 2024. All rights reserved.