Session WTF?


#1

Hi.

How to use session in ruby on rails ?
I try to make it work for hours, but it still doesn’t work…

In my controller I have this:

def identification
@current_user = User.new(params[:user])
ok = false
redir = ‘login_failed’
@remote_user = User.find(:all)
@remote_user.each do |r_user|
if (r_user.login == @current_user.login and
r_user.pass == @current_user.pass)
ok = true
end
end
if (ok)
session[:user_login] = params[:login]
session[:user_access] = params[:access]
redir = ‘list_article’
end
redirect_to :action => redir
end

I want to display the name of logged person.
In my views I have:

<%= if session[:user_login] then
“OK #{session[:user_login]}”
else
“Php RoX !”
end %>

But “session[:user_login]” is always empty.

Thanks.


#2

CptPingu wrote:

How to use session in ruby on rails ?
I try to make it work for hours, but it still doesn’t work…

You’re doing it basically right: if you set attributes of session, you
should be able to read them back.

Your code to set the session variables looks very confused though. I’d
bet that there’s at least one major bug in your identification method.
You should try logging the contents of the variables at various points
in it and use that to work out what’s going on.

  • Pete

#3

this piece of code:

@remote_user = User.find(:all)
@remote_user.each do |r_user|
  if (r_user.login == @current_user.login and
      r_user.pass == @current_user.pass)
    ok = true
  end

you’re iterating over an array of all of the users in the table, and you
set the ‘ok’ variable to true, if one of them matches. this is great,
but the next loop in the iteration will set ‘ok’ back to false, since
i’m guessing we’re not talking about a universe where all of the users
are a duplicate of the same person.
mmm.

if you add in a

  ok = true
     return

it should work.
else
“Php RoX !” (not)


#4

Better way to do the same:

def identification
if User.find(:conditions => [“login = ? and pass =
?”,params[:user][:login],params[:user][:pass]])
session[:user_login] = params[:login]
session[:user_access] = params[:access]
redirect_to :action => ‘list_article’
else
redirect_to :action => ‘login_failed’
end
end

def identification
@current_user = User.new(params[:user])
ok = false
redir = ‘login_failed’
@remote_user = User.find(:all)
@remote_user.each do |r_user|
if (r_user.login == @current_user.login and
r_user.pass == @current_user.pass)
ok = true
end
end
if (ok)
session[:user_login] = params[:login]
session[:user_access] = params[:access]
redir = ‘list_article’
end
redirect_to :action => redir
end

But “session[:user_login]” is always empty.