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
含routes.install_helpers(self)
调用的included
块指示,你将需要include
模块,以获得方法安装(所以extend
是出)。
如果您在类上下文中调用extend
,那么以下方法应该可以工作。试试这个:
Class MyModel
class << self
include Rails.application.routes.url_helpers
end
end
Class.root_path
这是MVC的错误方法。您应该在应用程序的控制器或帮助程序级别添加路由相关的方法。 –
重复http://stackoverflow.com/questions/341143/can-rails-routing-helpers-i-e-mymodel-pathmodel-be-used-in-models –
它是如何重复。他们将其添加为实例方法。我想将它添加为类方法。这就是我的问题:如何添加模块实例方法作为类方法 – user566245