未定义的局部变量或方法 `authenticate_admin' [英] undefined local variable or method `authenticate_admin'

查看:47
本文介绍了未定义的局部变量或方法 `authenticate_admin'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的博客控制器中查看我的新操作,但我不断收到以下错误消息:

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'

在我的博客控制器中,我想将新操作仅限于管理员(管理员和用户是两种不同的模型).我能够让它在另一个模型中工作.如果我没记错的话,助手对所有班级都开放.我还尝试将我的 admins helper 中的代码添加到 blogs helper,但这没有用.

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.

为什么我的博客控制器不能使用我的 authenticate_admin 方法?

感谢您的关注 :)

以下是相关文件:

blogs_controller.rb

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

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

推荐答案

在这种情况下,Helpers 可以在您的 Views 中访问,而不是在 Controllers 中.

In this case Helpers are accessible in your Views not in Controllers.

解决方案是将您的方法从 admins_helper.rb 移动到 ApplicationController 并将它们设置为 helper_methods.您将能够在 ControllersViews 中访问它们.

Solution is to move your methods from admins_helper.rb to ApplicationController and set them as helper_methods. You will be able to access them in your Controllers and Views.

示例:

class ApplicationController < ActionController::Base

  # Helpers
  helper_method :authenticate_admin

  def authenticate_admin
    deny_admin_access unless admin_signed_in?
  end 

end

阅读有关 helper_method 的文档:

http://api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html#method-i-helper_method

这篇关于未定义的局部变量或方法 `authenticate_admin'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆