Rails - How to use a Helper Inside a Controller

前端 未结 8 1240
生来不讨喜
生来不讨喜 2020-11-29 15:01

While I realize you are supposed to use a helper inside a view, I need a helper in my controller as I\'m building a JSON object to return.

It goes a little like this:

8条回答
  •  悲&欢浪女
    2020-11-29 15:50

    One alternative missing from other answers is that you can go the other way around: define your method in your Controller, and then use helper_method to make it also available on views as, you know, a helper method.

    For instance:

    
    class ApplicationController < ActionController::Base
    
    private
    
      def something_count
        # All other controllers that inherit from ApplicationController will be able to call `something_count`
      end
      # All views will be able to call `something_count` as well
      helper_method :something_count 
    
    end
    

提交回复
热议问题