Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"undefined method" when calling helper method from controller in Rails

Does anyone know why I get

undefined method `my_method' for #<MyController:0x1043a7410> 

when I call my_method("string") from within my ApplicationController subclass? My controller looks like

class MyController < ApplicationController   def show     @value = my_method(params[:string])   end end 

and my helper

module ApplicationHelper   def my_method(string)     return string   end end 

and finally, ApplicationController

class ApplicationController < ActionController::Base   after_filter :set_content_type   helper :all   helper_method :current_user_session, :current_user   filter_parameter_logging :password   protect_from_forgery # See ActionController::RequestForgeryProtection for details 
like image 863
Chad Johnson Avatar asked Mar 05 '10 18:03

Chad Johnson


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.

What is helper method 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 .


2 Answers

You cannot call helpers from controllers. Your best bet is to create the method in ApplicationController if it needs to be used in multiple controllers.

EDIT: to be clear, I think a lot of the confusion (correct me if I'm wrong) stems from the helper :all call. helper :all really just includes all of your helpers for use under any controller on the view side. In much earlier versions of Rails, the namespacing of the helpers determined which controllers' views could use the helpers.

I hope this helps.

like image 58
theIV Avatar answered Sep 19 '22 04:09

theIV


view_context is your friend, http://apidock.com/rails/AbstractController/Rendering/view_context

if you wanna share methods between controller and view you have further options:

  • use view_context
  • define it in the controller and make available in view by the helper_method class method http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method
  • define it in a shared module and include/extend
like image 24
Viktor Trón Avatar answered Sep 21 '22 04:09

Viktor Trón