简体   繁体   中英

sessions in Rails

I'm reading Agile web Development to learn Rails 3.0. The author is teaching us how to use sessions using this create method in the sessions controller.

def create 

if user = User.authenticate(params[:name], params[:password])
session[:user_id] = user.id
redirect_to admin_url
else
redirect_to login_url, :alert => "Invalid user/password combination"
end 

end

In the line

session[:user_id] = user.id

does the symbol :user_id exist somewhere before he assigns user.id to it? or is this symbol :user_id created at the moment that he assigns user.id to it? Is there a set number of symbols that belong to this 'session' or can you basically just create something with any name and assign anything to it?

It is created dynamically on the fly. You can see what is in the session by using the debugger and typing p session . If you are only storing string data, then you can pretty must store whatever you want, though there are size limitations. The default session is stored in a cookie, though you can also set your SessionStore to be on the server-side as well.

I'm not sure if you can change the name using a config file, but the session hash is a special variable that Rails uses. So you should stick to doing session[:my_var] = "whatever'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM