“undefined method” when calling helper method from controller in Rails

后端 未结 11 2023
傲寒
傲寒 2020-12-12 22:36

Does anyone know why I get

undefined method `my_method\' for #

when I call my_method(\"string\") from withi

相关标签:
11条回答
  • 2020-12-12 22:38

    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
    0 讨论(0)
  • 2020-12-12 22:40

    Maybe I'm wrong, but aren't the helpers just for views? Usually if you need a function in a controller, you put it into ApplicationController as every function there is available in its childclasses.

    0 讨论(0)
  • 2020-12-12 22:41

    As far as i know, helper :all makes the helpers available in the views...

    0 讨论(0)
  • 2020-12-12 22:41

    Try appending module_function(*instance_methods) in your helper modules, after which you could directly call those methods on the module itself.

    0 讨论(0)
  • 2020-12-12 22:46

    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.

    0 讨论(0)
  • 2020-12-12 22:49

    helpers are for views, but adding a line of code to include that helper file in ApplicationController.rb can take care of your problem. in your case, insert the following line in ApplicationController.rb:

    include ApplicationHelper
    
    0 讨论(0)
提交回复
热议问题