Rails - How to use a Helper Inside a Controller

Ruby on-RailsRuby on-Rails-3Ruby on-Rails-5

Ruby on-Rails Problem Overview


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:

def xxxxx

   @comments = Array.new

   @c_comments.each do |comment|
   @comments << {
     :id => comment.id,
     :content => html_format(comment.content)
   }
   end

   render :json => @comments
end

How can I access my html_format helper?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can use

  • helpers.<helper> in Rails 5+ (or ActionController::Base.helpers.<helper>)
  • view_context.<helper> (Rails 4 & 3) (WARNING: this instantiates a new view instance per call)
  • @template.<helper> (Rails 2)
  • include helper in a singleton class and then singleton.helper
  • include the helper in the controller (WARNING: will make all helper methods into controller actions)

Solution 2 - Ruby on-Rails

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!

Solution 3 - Ruby on-Rails

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

Solution 4 - Ruby on-Rails

My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...

Solution 5 - Ruby on-Rails

In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController.

Solution 6 - Ruby on-Rails

Before Rails 5, you have to include the helper module.

In newer versions, you can use helpers in your controller with the helpers (plural) object.

  class UsersController
    def index
      helpers.my_helper_method_name(even_pass_arg_here)
    end
  end

https://www.rubyguides.com/2020/01/rails-helpers/

Solution 7 - Ruby on-Rails

In Rails 5+ you can simply use the function as demonstrated below with simple example:

module ApplicationHelper
  # format datetime in the format #2018-12-01 12:12 PM
  def datetime_format(datetime = nil)
    if datetime
      datetime.strftime('%Y-%m-%d %H:%M %p')
    else
      'NA'
    end
  end
end

class ExamplesController < ApplicationController
  def index
    current_datetime = helpers.datetime_format DateTime.now
    raise current_datetime.inspect
  end
end

> #OUTPUT > "2018-12-10 01:01 AM"

Solution 8 - Ruby on-Rails

In rails 6, simply add this to your controller:

class UsersController < ApplicationController
  include UsersHelper
  
  # Your actions

end

Now the user_helpers.rb will be available in the controller.

Solution 9 - Ruby on-Rails

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

Solution 10 - Ruby on-Rails

class MyController < ApplicationController
    # include your helper
    include MyHelper
    # or Rails helper
    include ActionView::Helpers::NumberHelper

    def my_action
      price = number_to_currency(10000)
    end
end

In Rails 5+ simply use helpers (helpers.number_to_currency(10000))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnApprenticeView Question on Stackoverflow
Solution 1 - Ruby on-RailsgrosserView Answer on Stackoverflow
Solution 2 - Ruby on-RailsXavier HoltView Answer on Stackoverflow
Solution 3 - Ruby on-RailsGerry ShawView Answer on Stackoverflow
Solution 4 - Ruby on-RailsThadeu Esteves Jr.View Answer on Stackoverflow
Solution 5 - Ruby on-RailsFrancoView Answer on Stackoverflow
Solution 6 - Ruby on-Railsaldrien.hView Answer on Stackoverflow
Solution 7 - Ruby on-RailsRavistmView Answer on Stackoverflow
Solution 8 - Ruby on-RailsstevecView Answer on Stackoverflow
Solution 9 - Ruby on-Railssandre89View Answer on Stackoverflow
Solution 10 - Ruby on-RailsalbertmView Answer on Stackoverflow