0

我需要控制用户当前是否登录了我的网站,但是我在初始化用于此控件的变量时遇到了问题:session[:user_id].

这是我使用的代码:

def authenticate_user
    if session[:user_id].nil?
      redirect_to(:controller => 'users', :action => 'index')
      return false
    else
      # set current_user by the current user object
      @current_user = User.find session[:user_id]
      return true
    end
 end

我在我想要阻止未登录用户的所有控制器中调用此方法,使用以下代码:

before_filter :authenticate_user, :only => [:index,:show,:edit]

在我看来,问题出在session[:user_id]变量上,当用户访问我的网站时,变量没有初始化,nil因此控件不起作用。

我可以在索引页的控制器中初始化变量,但是这种方法是错误的。

例如,当我在没有登录的情况下请求此页面时:

127.0.0.1:3000/菜单

错误是:

undefined local variable or method `authenticate_user' for #<MenusController:0x007faa6e5a4c20>

更新:

现在错误不再出现,但是当用户尚未登录时 条件:

if session[:user_id].nil? 

未验证。

如果我在用户控制器中声明此方法:

before_filter :initializes



def initializes
    session[:user_id]=nil;
  end

有用!此外,如果用户不需要“索引页面(登录页面)”但我不明白为什么

4

3 回答 3

1

尝试这个

在你的 application_controller.rb

def current_user
 renturn unless session[:user_id]
 @current_user ||= User.find(session[:user_id])
end


def authenticate_user!
  redirect_to(:controller => 'users', :action => 'index') unless current_user
end

并且操作索引不应强制登录,因为除非用户未登录,否则我们将重定向到那里。

在你的 users_controller.rb

before_filter :authenticate_user!, :only => [:show,:edit]
于 2013-06-18T10:59:50.330 回答
0

您定义了 authenticate_use 但您的过滤器调用中有 authenticate_user

于 2013-06-18T11:20:45.843 回答
-1

您应该使用 Devise gem 进行身份验证https://github.com/plataformatec/devise

于 2013-06-19T13:09:11.563 回答