use*_*245 5 ruby routes ruby-on-rails
我如何将类似"root_path"的rails路由助手添加到像my_model.rb这样的类作为类方法?
所以我的班级是这样的:
Class MyModel
def self.foo
return self.root_path
end
end
MyModel.foo
Run Code Online (Sandbox Code Playgroud)
以上操作无效,因为类MyModel不响应root_path
这就是我所知道的:
Rails.application.routes.url_helpers,但只添加模块的方法作为实例方法Rails.application.routes.url_helpers但它没有用请随时上学我:)
Stu*_*t M 13
通常不需要从模型访问URL路由.通常,您只需要在处理请求时或在渲染视图时(例如,如果您格式化链接URL)从控制器访问它们.
因此,您只需root_path从控制器或视图中调用,而不是向模型对象询问根路径.
编辑
如果您只是对您无法将模块的方法作为类方法包含在类中的原因感兴趣,我不会期望一个简单include的工作,因为这将包括模块的方法和类中的实例方法.
extend通常会工作,但在这种情况下,它不是由于url_helpers方法的实现方式.来自actionpack/lib/action_dispatch/routing/route_set.rb源
def url_helpers
@url_helpers ||= begin
routes = self
helpers = Module.new do
...
included do
routes.install_helpers(self)
singleton_class.send(:redefine_method, :_routes) { routes }
end
Run Code Online (Sandbox Code Playgroud)
included包含该routes.install_helpers(self)调用的块表示您将需要include该模块以便安装方法(因此extend已经完成).
如果extend在类上下文中调用,则以下内容应该有效.试试这个:
Class MyModel
class << self
include Rails.application.routes.url_helpers
end
end
Class.root_path
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5767 次 |
| 最近记录: |