undefined局部变量或方法`authenticate_admin'

时间:2022-02-22 11:55:43

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?

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

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

1 个解决方案

#1


3  

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

在这种情况下,可以在视图中访问助手,而不是在控制器中。

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.

解决方案是将方法从admins_helper.rb移动到ApplicationController并将它们设置为helper_methods。您可以在控制器和视图中访问它们。

Example:

class ApplicationController < ActionController::Base

  # Helpers
  helper_method :authenticate_admin

  def authenticate_admin
    deny_admin_access unless admin_signed_in?
  end 

end

Read documentation about helper_method:

阅读有关helper_method的文档:

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

#1


3  

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

在这种情况下,可以在视图中访问助手,而不是在控制器中。

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.

解决方案是将方法从admins_helper.rb移动到ApplicationController并将它们设置为helper_methods。您可以在控制器和视图中访问它们。

Example:

class ApplicationController < ActionController::Base

  # Helpers
  helper_method :authenticate_admin

  def authenticate_admin
    deny_admin_access unless admin_signed_in?
  end 

end

Read documentation about helper_method:

阅读有关helper_method的文档:

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