Rails 3 查看模型中的辅助方法
我的模型中有一个类方法,我需要从我的视图助手之一访问一个方法。目前我包括 include TalkHelper
,但我仍然收到 NoMethodError。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的模型中,您可以执行如下操作:
或
最佳解决方案是重构您的代码,以便您根本不需要从模型。这不是 RoR 方式。正如其他人指出的,您可以将帮助程序代码提取到 lib 文件夹。
有关更多信息,请参阅:
http://railscasts.com/episodes/132-helpers-outside -视图
In your model, you can do something like the following:
OR
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. As others point out, you could extract the helper code to lib folder.
See this for more info:
http://railscasts.com/episodes/132-helpers-outside-views
您可以将 helper 放在 lib 文件夹中并将它们包含在其中的任何位置。
像这样:
lib/some_helper.rb
You may place helper in your lib folder and include them anythere.
Like this:
lib/some_helper.rb
如果您需要类方法中的帮助器,则需要
扩展
它,而不是包含
它。请注意视图上下文之外的帮助程序,因为帮助程序可能依赖于控制器或请求上下文中的其他内容,而这些在您的模型中不可用。
If you need the helper in a class method you'd need to
extend
it, notinclude
it.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.