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
Helpers are to be used with templates, ie. views, not in controllers. That's why you can't access the method. If you'd like to share a method between two controllers, you'd have to define it in ApplicationController, for instance. helper :all says that any method you define in any helper file in app/helpers directory will be available to any template.
The time when I find this to be most needed is for writing the flash, or custom error checkers. Its nice to use things like link_to helpers in the flash message under some circumstances. I use the following solution to get ActionView helpers into the controller. Be advised that as was mentioned above, this breaks the MVC separation, so if anyone else has a better idea, let me know!
Below ApplicationController add this:
class Something
include Singleton
include ActionView::Helpers::UrlHelper
end
and inside the ApplicationController, add
def foo
Something.instance
end
and finally, in the controller where you want to access the helper code:
messages << "<li class='error'>Your have an Error!<%= foo.link_to('Fix This', some_path) %></li>"
Hope that helps in some way!
If you change your application_controller.rb file to this...
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
...then all helpers will be available to all controllers.
One way to get at your helper methods is simply to include your helper file.
include LoginHelper
cool_login_helper_method(x,y,z)
This brings all the methods from that helper module into scope in your controller. That's not always a good thing. To keep the scope separate, create an object, imbue it with the powers of that helper, and use it to call the methods:
login_helper = Object.new.extend(LoginHelper)
login_helper.cool_login_helper_method(x,y,z)
helper :all
makes all of your helper methods from all of your helper modules available to all of your views, but it does nothing for your controllers. This is because helper methods are designed for use in views and generally shouldn't be accessed from controllers. In newer versions of Rails, this option is always on for every controller by default.
Please try include SessionsHelper
in ApplicationController
class ApplicationController < ActionController::Base
include SessionsHelper
...
end
Controller can't access helper methods automatically. We must include them in app controller.
module ApplicationHelper
def hello_message
"Hello World"
end
end
class ApplicationController < ActionController::Base
include ApplicationHelper
def message
hello_message
end
end