我想将应用程序的根目录设置为引擎控制器的操作。我以为我的config/routes.rb
可以做到:
root action: :show, controller: :pages, module: :MyEngine
但是我遇到uninitialized constant PagesController
错误。是否在自动加载引擎控制器之前设置了路线?
答案 0 :(得分:0)
我相信引擎的控制器要等到安装后才能加载。我找不到找到想要的方式路由到引擎的方法,但是我确实找到了以下方法:
1)将引擎安装在根目录下(可能不是严格地想要的)
mount MyEngine => '/', as: :myengine
2)将root重定向到引擎
# For redirecting to the engine's mount
root to: redirect { Rails.application.routes.url_helpers.myengine_path }
# For a specific engine path
root to: redirect { MyEngine.routes.url_helpers.some_path }
如果您不介意对引擎路径进行硬编码,则可以:
root to: '/myengine/url'
在路线中可能存在更好的处理这些助手的方法,但这是我能找到的最直接的方法。我确实在this answer上偶然发现了一个稍微相关的问题,该问题提到专门为此类事情创建助手。对其进行修改以使其与引擎一起使用可能会给出以下信息:
class UrlRedirectHelper
# This makes the case where you just want to use the main app's routes less verbose
def self.method_missing(method, *args, **kwargs)
new.public_send(method, *args, **kwargs)
end
# This is some entirely unnecessary sugar, I just like the way it reads
def self.for(engine)
new(engine)
end
def initialize(engine = Rails.application)
@engine = engine
end
# This is called by `redirect` when it's preparing to redirect the user
def call(_params, _request)
url_helpers.public_send(@method, *@args, **@kwargs)
end
def method_missing(method, *args, **kwargs)
super unless url_helpers.respond_to? method
@method = method
@args = args
@kwargs = kwargs
self
end
private
# you could also `delegate` this, but it keeps the API cleaner to make it private
def url_helpers
@engine.routes.url_helpers
end
end
然后像这样使用它:
get :somepath, to: redirect(UrlRedirectHelper.some_other_path)
# or, for an engine
get :somepath, to: redirect(UrlRedirectHelper.for(MyEngine).some_other_path)
答案 1 :(得分:0)
我明确声明了我正在使用的控制器,而在config/routes.rb
中没有名称间隔。
PagesController = MyEngine::PagesController
root action: :show, controller: :pages
做到了。我想知道我是否发现了module
选项的错误吗?