NoMethodError when trying to invoke helper method from Rails controller

前端 未结 14 1195
滥情空心
滥情空心 2020-11-30 20:05

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

14条回答
  •  旧时难觅i
    2020-11-30 20:43

    Helper Methods from 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

    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.

提交回复
热议问题