NoMethodError when trying to invoke helper method from Rails controller

前端 未结 14 1194
滥情空心
滥情空心 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条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 20:39

    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 << "
  • Your have an Error!<%= foo.link_to('Fix This', some_path) %>
  • "

    Hope that helps in some way!

提交回复
热议问题