[英]Rails 3 View helper method in Model
I have a class method in my model, and I need to access a method from one of my view helpers. 我的模型中有一个类方法,我需要从一个视图助手访问一个方法。 Currently I am including
include TalkHelper
, but I still get a NoMethodError. 目前我
include TalkHelper
,但我仍然得到NoMethodError。
In your model, you can do something like the following: 在您的模型中,您可以执行以下操作:
ApplicationController.helpers.your_helper_method
OR 要么
YourController.helpers.your_helper_method
The best solution is to refactor your code so that you don't need to call view helper code at all from models. 最好的解决方案是重构代码,这样就不需要从模型中调用视图助手代码了。 It is not the RoR way.
这不是RoR的方式。 As others point out, you could extract the helper code to lib folder.
正如其他人指出的那样,您可以将帮助程序代码解压缩到lib文件夹。
See this for more info: 有关详细信息,请参阅此
http://railscasts.com/episodes/132-helpers-outside-views http://railscasts.com/episodes/132-helpers-outside-views
You may place helper in your lib folder and include them anythere. 您可以在lib文件夹中放置帮助程序并将其包含在其中。 Like this: lib/some_helper.rb
像这样:lib / some_helper.rb
module SomeHelper
def somedef
#your code there
end
end
If you need the helper in a class method you'd need to extend
it, not include
it. 如果您需要在类方法中使用帮助器,则需要对其进行
extend
,而不是include
它。
module TalkHelper
def woo; 'hoo' end
end
class MyClass
extend TalkHelper
def self.boo; woo end
end
MyClass.boo #=> 'hoo'
Just be careful with helpers outside of the view context, as helpers may depend on controller
, or something else from the context of a request, which will not be available in your model. 请注意视图上下文之外的帮助程序,因为帮助程序可能依赖于
controller
或请求上下文中的其他内容,而这些内容在您的模型中不可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.