在Rails Controller 或 View 的范围内:
如何查询Rails路由机制以将相对的URL字符串(例如“/controllername/action/whatever”)转换为负责处理该请求的 Controller 类?
我想做这样的事情:
controllerClass = someMethod("/controllername/action/whatever")
其中contorllerClass是Class的实例。
我不想对例如路由约定做任何假设。上面示例中的“controllername”始终是 Controller 的名称(因为不是)。
最佳答案
在这里建立Carlos:
path = "/controllername/action/whatever"
c_name = ActionController::Routing::Routes.recognize_path(path)[:controller]
controllerClass = "#{c_name}_controller".camelize.constantize.new
将为您提供 Controller 类的新实例。
关于ruby-on-rails - 如何确定给定URL字符串的Controller类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1056950/