2012-02-11 57 views
0

我試圖實現Rails的一個簡單的登錄系統,但是當我嘗試顯示的用戶名已登錄的用戶,我得到這個錯誤:不能轉換符號爲整

can't convert Symbol into Integer 
Extracted source (around line #60): 

57:  </ul> 
58:  <% if session[:logged_in] %> 
59:   <% user = session[:user] %> 
60:   <p class="pull-right">Howdy, <strong><%= user[:username] %></strong>!</p> 
61:  <% end %> 
62:  </div> 
63: </div> 

我的模型代碼是在這裏:

require 'digest' 

class User < ActiveRecord::Base 

before_save {|user| user.password = Digest::SHA1.hexdigest(user.password)} 
attr_accessible :username, :password, :email 
validates_length_of :username, :password, :minimum => 7 
validates_presence_of :username,:password,:email, :on => :create 
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i 

end 

這是我如何設置會話[:用戶]:

def create 
    if User.find(:all, :conditions => {:username => params[:username], :password => Digest::SHA1.hexdigest(params[:username])}) 
     user = User.find(:all, :conditions => {:username => params[:username], :password => Digest::SHA1.hexdigest(params[:password])}) 
     session[:user] = user 
     session[:logged_in] = true 
     redirect_to(:root, :notice => "Thanks for logging in!") 
    else 
     redirect_to(:new, :notice => "You supplied an invalid username/password combination.") 
    end 
end 
+0

如何代碼看起來象,設置'會話[:用戶]'?代碼中失敗點的'session [:user]'的價值是什麼? – 2012-02-11 04:39:04

回答

5

大概session[:user]是不是一個已h,就像你期望的那樣,但是是一個Array。因此使用除整數以外的任何東西來下標它是無效的。

如何解決這個問題?更改實際設置會話變量的代碼(如session[:user] = XYZ)。

編輯:User.find(:all, ...)返回一個數組,所以我認爲,要指定數組session[:user]。您應該只分配找到的第一個用戶(實際上,應該只有一個符合條件)。更妙的是,你應該只在用戶名存儲在會話中,如果需要從數據庫中獲取它:

def create 
    user = User.where(:username => params[:username], :password => Digest::SHA1.hexdigest(params[:username])).first 
    if user 
    session[:user_id] = user.id 
    else 
    redirect_to(:new, :notice => "You supplied an invalid username/password combination.") 
    end 
end 

然後在您的視圖相關聯的動作:

def ... 
    @user = User.find(session[:user_id]) 
    unless @user 
    # redirect to error page, user was deleted in the meantime 
    end 
end 

然後在視圖:

<%= @user.username %> 
1

將整個用戶對象轉儲到您的會話中是一個壞主意,可能是爲什麼你沒有找回你期望的東西。你應該在你的User類上實現類似#to_session的東西,它返回一個包含最小必需信息的散列。喜歡的東西:

def to_session 
    {:id => id, :username => username, :email => email} 
end 

然後,當你設置會話:

session[:user] = user.to_session 
相關問題