已安装的Rails引擎中的命名路线 [英] Named routes in mounted rails engine

查看:123
本文介绍了已安装的Rails引擎中的命名路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制造一个小型的Rails引擎,它是这样安装的:

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

mount BasicApp::Engine => "/app"

使用这个答案验证引擎中的所有路线均应符合以下条件:

Using this answer I have verified that all the routes in the engine are as the should be:

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

However - when I (inside the engine) link to a named route (defined inside the engine) I get this error

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

正在运行的"rake route"清楚地验证了"new_post"应该是一个命名路径,因此我不知道为什么Rails(3.1.0)无法弄清楚它.欢迎任何帮助

Running "rake route" clearly verifies that "new_post" should be a named path, so I have no idea why Rails (3.1.0) can't figure it out. Any help is welcome

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

my config/route.rb (for the engine) look like this

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

我应该补充一点,它是隔离的引擎.但是,像main_app.root_path这样的路径可以正常工作-而root_path则不行

I should add that it is and isolated engine. However paths like main_app.root_path works fine - while root_path does not

推荐答案

正确的方法

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

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

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

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

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

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

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)

这篇关于已安装的Rails引擎中的命名路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆