无法将符号转换为整数

时间:2012-02-11 04:34:50

标签: ruby-on-rails ruby authentication hash symbols

我正在尝试在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

这就是我设置session [:user]:

的方法
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

2 个答案:

答案 0 :(得分:5)

可能session[:user]不是Hash,正如您所期望的那样,而是一个数组。因此,使用除整数之外的任何内容来订阅它是无效的。

如何解决这个问题?更改实际设置会话变量的代码(如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 :(得分:1)

将整个User对象转储到您的会话中是一个坏主意,这可能就是为什么您没有收回您的期望。您应该在User类上实现类似#to_session的内容,以返回具有所需最少信息的哈希。类似的东西:

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

然后当您设置会话时:

session[:user] = user.to_session