2013-07-23 26 views
5

我如何添加像“root_path”类似my_model.rb的路线助手作为类的方法添加导轨路线助手作为类的方法

所以我的课是这样的:

Class MyModel 

    def self.foo 
    return self.root_path 
    end 

end 

MyModel.foo 

以上不工作,因为类为MyModel不响应root_path

这是我知道的:

  1. 我可以使用包括Rails.application.routes.url_helpers,但只添加模块的方法作为实例方法
  2. 我试过做扩展Rails.application.routes.url_helpers没有工作

请随时到学校我:)

+0

这是MVC的错误方法。您应该在应用程序的控制器或帮助程序级别添加路由相关的方法。 –

+0

重复http://stackoverflow.com/questions/341143/can-rails-routing-helpers-i-e-mymodel-pathmodel-be-used-in-models –

+0

它是如何重复。他们将其添加为实例方法。我想将它添加为类方法。这就是我的问题:如何添加模块实例方法作为类方法 – user566245

回答

12

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 
+0

以及我明白你的观点,但那不是我的问题。我在问如何将模块的实例方法添加为类方法。我知道扩展应该可行,但在我提到的情况下它不起作用。你知道为什么吗? – user566245

+0

@ user566245陷阱。我已经更新了我的答案,请再看一下 –

+0

@ user566245是否为您工作?请试试看,如果结果正确无误,请接受答案,谢谢! –