Rails - How to use a Helper Inside a Controller

前端 未结 8 1230
生来不讨喜
生来不讨喜 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 16:05

    Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

    Option 1: Probably the simplest way is to include your helper module in your controller:

    class MyController < ApplicationController
      include MyHelper
    
      def xxxx
        @comments = []
        Comment.find_each do |comment|
          @comments << {:id => comment.id, :html => html_format(comment.content)}
        end
      end
    end
    

    Option 2: Or you can declare the helper method as a class function, and use it like so:

    MyHelper.html_format(comment.content)
    

    If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

    module MyHelper
      def self.html_format(str)
        process(str)
      end
    
      def html_format(str)
        MyHelper.html_format(str)
      end
    end
    

    Hope this helps!

    0 讨论(0)
  • 2020-11-29 16:05

    In Rails 5 use the helpers.helper_function in your controller.

    Example:

    def update
      # ...
      redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
    end
    

    Source: From a comment by @Markus on a different answer. I felt his answer deserved it's own answer since it's the cleanest and easier solution.

    Reference: https://github.com/rails/rails/pull/24866

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