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.
Asked
Active
Viewed 1.8k times
8

LanguagesNamedAfterCofee
- 5,782
- 7
- 45
- 72
3 Answers
42
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. As others point out, you could extract the helper code to lib folder.
See this for more info:

Matthias
- 1,884
- 2
- 18
- 35

Innerpeacer
- 1,321
- 12
- 20
-
I ended up following your advice and refractoring my code so that I did not have to use the helper method in the model. – LanguagesNamedAfterCofee Sep 19 '11 at 03:08
8
You may place helper in your lib folder and include them anythere. Like this: lib/some_helper.rb
module SomeHelper
def somedef
#your code there
end
end

railscard
- 1,848
- 16
- 12
6
If you need the helper in a class method you'd need to extend
it, not include
it.
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.

numbers1311407
- 33,686
- 9
- 90
- 92