繁体   English   中英

安装导轨引擎中的命名路线

[英]Named routes in mounted rails engine

我正在制作一个小型导轨引擎,我像这样安装:

mount BasicApp::Engine => "/app"

使用这个答案,我已经验证引擎中的所有路由都应该是:

但是 - 当我(在引擎内)链接到命名路由(在引擎内定义)时,我收到此错误

undefined local variable or method `new_post_path' for #<#<Class:0x000000065e0c08>:0x000000065d71d0>

运行“rake route”清楚地验证“new_post”应该是一个命名路径,所以我不知道为什么Rails(3.1.0)无法弄清楚。 欢迎任何帮助

我的 config/route.rb(用于引擎)看起来像这样

BasicApp::Engine.routes.draw do
  resources :posts, :path => '' do
                resources :post_comments
                resources :post_images
        end
end

我应该补充一点,它是独立的引擎。 然而,像 main_app.root_path 这样的路径工作正常 - 而 root_path 没有

正确的方式

我相信最好的解决方案是在引擎的路由代理上调用new_post_path ,它可用作辅助方法。 在您的情况下,助手方法将默认为basic_app_engine ,因此您可以在您的视图或助手中调用basic_app_engine.new_post_path

如果需要,您可以通过以下两种方式之一设置名称。

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

或者

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

无论哪种情况,您都可以在您的视图或助手中调用basic.new_posts_path

其它的办法

另一种选择是不使用安装的引擎,而是让引擎直接将路由添加到应用程序。 Thoughtbot 的 HighVoltage 可以做到这一点。 我不喜欢这个解决方案,因为当你添加很多引擎时它很可能会导致命名空间冲突,但它确实有效。

# 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)

在 Rails 4 上, engine_name指令对我不起作用。
为了从引擎自己的视图或控制器访问引擎路由中定义的命名路由,我最终使用了verbose

BasicApp::Engine.routes.url_helpers.new_post_path

我建议定义一个简单的辅助方法以使其更有用

# 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

有了这个,你现在可以使用

basic_app_engine.new_post_path

如果您需要从引擎访问您的主要应用程序助手,您可以使用main_app

main_app.root_path

在您的应用程序中使用以下内容访问引擎路线

MyApp::Engine.routes.url_helpers.new_post_path

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM