gpt4 book ai didi

ruby-on-rails - 安装 rails 引擎中的命名路线

转载 作者:行者123 更新时间:2023-12-03 07:48:25 26 4
gpt4 key购买 nike

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

mount BasicApp::Engine => "/app"

使用this answer我已验证引擎中的所有路由均应如此:

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

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

运行“rakeroute”清楚地验证了“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,因此您可以在 View 或帮助程序中调用 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'

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

另一种方式

另一个选择是不使用已安装的引擎,而是让引擎将路由直接添加到应用程序。 Thoughtbot's 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)

关于ruby-on-rails - 安装 rails 引擎中的命名路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8029192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com