I\'m getting a NoMethodError
when trying to access a method defined in one of my helper modules from one of my controller classes. My Rails application uses the
There are two ways to do this: either to create a module or use @template variable. Check this out for more details http://www.shanison.com/?p=305
If you only have ApplicationHelper inside your app/helpers
folder than you have to load it in your controller with include ApplicationHelper
. By default Rails only load the helper module that has the same name as your controller. (e.g. ArticlesController will load ArticlesHelper). If you have many models (e.g. Articles; Posts; Categories) than you have to upload each one in you controller. the docs
Helper
module PostsHelper
def find_category(number)
return 'kayak-#{number}'
end
def find_other_sport(number)
"basketball" #specifying 'return' is optional in ruby
end
end
module ApplicationHelper
def check_this_sentence
'hello world'
end
end
Example Controller
class ArticlesController < ApplicationController
include ApplicationHelper
include PostsHelper
#...and so on...
def show#rails 4.1.5
#here I'm using the helper from PostsHelper to use in a Breadcrumb for the view
add_breadcrumb find_other_sport(@articles.type_activite), articles_path, :title => "Back to the Index"
#add_breadcrumb is from a gem ...
respond_with(@articles)
end
end
helper :all
makes all the helpers (yes, all of them) available in the views, it does not include them into the controller.
If you wish to share some code between helper and controller, which is not very desirable because helper is UI code and controller is, well, controller code, you can either include the helper in the controller, or create a separate module and include that in the controller and the helper as well.
To use the helper methods already included in the template engine:
@template
variable. Example usage of calling 'number_to_currency' in a controller method:
# rails 3 sample
def controller_action
@price = view_context.number_to_currency( 42.0 )
end
# rails 2 sample
def controller_action
@price = @template.number_to_currency( 42.0 )
end
For Rails 3, use the view_context
method in your controller:
def foo
view_context.helper_method
...
Here's an example: http://www.christopherirish.com/2011/10/13/no-view_context-in-rails-3-1-changes/
if you need to share a method between a controller and helper/view, you can just define via 'helper_method' in the top of the controller:
class ApplicationController < ActionController::Base
helper_method :my_shared_method
...
def my_shared_method
#do stuff
end
end
hope that helps