I’m trying to view my new action in my blogs controller, but I keep getting the following error message:
NameError in BlogsController#new
undefined local variable or method `authenticate_admin'
In my blogs controller, I want to restrict the new action to admins only (admins and users are two different models). I was able to get this to work in another model. If I’m not mistaken, helpers are open to all classes. I also tried to add the code from my admins helper to the blogs helper, but that didn’t work.
Why can’t my blogs controller use my authenticate_admin method?
Thanks for lookign 🙂
Here are relevant files:
blogs_controller.rb
class BlogsController < ApplicationController
before_filter :authenticate_admin, :only => [:new]
def new
@blog = Blog.new
@title = "New Article"
end
end
admins_helper.rb
def authenticate_admin
deny_admin_access unless admin_signed_in?
end
def deny_admin_access
redirect_to admin_login_url, :notice => "Please sign in as admin to access this page."
end
def admin_signed_in?
!current_admin.nil?
end
def current_admin
@current_admin ||= Admin.find(session[:admin_id]) if session[:admin_id]
end
In this case
Helpersare accessible in yourViewsnot inControllers.Solution is to move your methods from admins_helper.rb to
ApplicationControllerand set them ashelper_methods. You will be able to access them in yourControllersandViews.Example:
Read documentation about
helper_method:http://api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html#method-i-helper_method