Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoMethodError when trying to invoke helper method from Rails controller

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 helper class method with the :all symbol as shown below:

class ApplicationController < ActionController::Base   helper :all   .   . end 

My understanding is that this should make all of my controller classes automatically include all of the helper modules within the app/helpers directory, therefore mixing in all of the methods into the controllers. Is this correct?

If I explicitly include the helper module within the controller then everything works correctly.

like image 487
John Topley Avatar asked Jan 17 '09 18:01

John Topley


People also ask

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.

How do helpers work in Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.


1 Answers

To use the helper methods already included in the template engine:

  • Rails 2: use the @template variable.
  • Rails 3: has the nice controller method view_context

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 
like image 165
gamecreature Avatar answered Oct 04 '22 18:10

gamecreature