3

More newbie issues.

I understand that if I define a method in my application helper, it is available to the entire app code.

In my applicaton helper, I have:

def primary_user_is_admin

  if current_user
    user_login_roles = JSON.parse(current_user.role)
    if user_login_roles["admin"]
      return 1
    end
  end
  return nil
end

If I call it from the categories_controller:

if !primary_user_is_admin
  redirect_to root_url
end

I get an error message: undefined local variable or method `primary_user_is_admin'

This also happens if I put the primary_user_is_admin code in the registrations_helper.rb file

However, if I use it in any of the views (views/user/edit.html.erb for instance)

<% if primary_user_is_admin %>
<% end >

then it works. What am I missing?

EastsideDev
  • 6,257
  • 9
  • 59
  • 116
  • possible duplicate of ["undefined method" when calling helper method from controller in Rails](http://stackoverflow.com/questions/2388932/undefined-method-when-calling-helper-method-from-controller-in-rails) – KL-7 Jun 07 '12 at 16:10

2 Answers2

10

Helpers are not included into a controller by default. You can

include ApplicationHelper

To gain access to the methods in the ApplicationHelper module. The previous discussion has a bunch of useful solutions for accessing helpers in controller.

Community
  • 1
  • 1
mguymon
  • 8,946
  • 2
  • 39
  • 61
  • any idea on how to include the application helper in an initializer:: http://stackoverflow.com/questions/23035947/rails-4-use-application-helpers-inside-initializers – Chris Hough Apr 12 '14 at 21:01
4

Methods defined in helpers are only available to views by default. You have to 'include ApplicationHelper' in the applications controller to get access to this method in the controllers.

cdesrosiers
  • 8,862
  • 2
  • 28
  • 33