I’m trying to implement a simple login system in Rails, but when I try to display the username of a logged in user, I get this error:
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>
My model code is here:
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
This is how I set 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
Probably
session[:user]is not a Hash, as you expect it to be, but an Array. Thus subscripting it with anything other than an integer is not valid.How to fix this? Change the code that is actually setting the session variable (like
session[:user] = XYZ).EDIT:
User.find(:all, ...)returns an array, so as I assumed, you are assigning an array tosession[:user]. You should only assign the first user found (and in fact, there should be only one matching the criteria). Even better, you should only store the username in the session and fetch it from the database if needed:Then in the action associated with your view:
Then in the view: