RailsTutorial.org - 第8章 - signed_in?投掷错误

时间:2012-09-07 05:38:09

标签: ruby-on-rails ruby ruby-on-rails-3 railstutorial.org

如果用户已登录,我正在尝试显示导航栏。

在我的application.html.erb中,我有一行 <% if signed_in? %> - 导致错误:

NoMethodError in Static_pages#home

undefined method '[]' for nil:NilClass

Extracted source (around line #16):

13:   </head>
14:   <body>
15: 
16:     <% if signed_in? %>
17:      <div class="navbar navbar-fixed-top">
18:       <div class="navbar-inner">
19:         <div class="container">`

这是我的 SessionsHelper:

def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
end

def signed_in?
    !current_user.nil?
end

def current_user=(user)
    @current_user = user
end

def current_user
    puts 'current_user called'
    @current_user ||= User.find_by_remember_token(cookies.permanent[:remember_token])
end

def sign_out
    self.current_user = nil
    cookies.delete(:remember_token)
end

我的 ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery
  include SessionsHelper
end

我似乎无法弄清楚为什么!current_user.nil?打破了网页。当我在!current_user.nil?方法中注释掉signed_in?时,可以在不破坏页面的情况下调用它。但我显然没有得到我希望的signed_in值。

1 个答案:

答案 0 :(得分:3)

此处引发了异常:cookies.permanent[:remember_token]

所以,cookies.permanent是零

---- EDITED

得到它,

仅将cookies.permanent[:remember_token] =用于撰写,但请将其读作cookies[:remember_token]