“会话"从何而来? [英] Where does 'session' come from?
问题描述
我正在我的 rails 应用程序中构建一个会话控制器,我只是不确定为什么有些东西在这里工作.在创建和销毁操作中,session[index]
被分配给 nil 或用户 ID.但是这个会话哈希没有在任何地方定义(据我所知).为什么这是有效的?谁能帮我澄清一下?
I'm building a sessions controller in my rails app, and I'm just not sure why something is working here. In the create and destroy actions, session[index]
is assigned to either nil or a user id. But this sessions hash isn't defined anywhere (as far as I can see). Why is this working? Can anyone clarify this for me?
(为了清楚起见,没有会话模型)
(for the sake of clarity, there is no sessions model)
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to products_url, :note => "Logged in!"
else
render "new"
end
def destroy
session[:user_id] = nil
redirect_to products_url, :notice => "Logged out!"
end
end
推荐答案
session
实例方法的功能类似于 Hash,并且是 Rails API 的一部分.
The session
instance method functions like a Hash and is part of the Rails API.
Rails 完成设置加密、防篡改会话数据存储的所有工作.默认情况下,会话数据在浏览器中保存为 cookie.您可以指定其他存储机制,但 CookieStore
是默认的,也是最方便的.
Rails does all the work of setting up an encrypted, tamperproof session datastore. By default, session data is saved as a cookie in the browser. You can specify other storage mechanisms but CookieStore
is the default and the most convenient.
CookieStore
默认设置在 config/initializers/session_store.rb 文件中:
The CookieStore
default is set in the config/initializers/session_store.rb file:
Rails.application.config.session_store :cookie_store, key: '_learn-rails_session'
您可以在 Rails 中了解有关会话的更多信息:
You can learn more about sessions in Rails:
有关更多信息,我编写了一个 Rails Devise 教程,展示了会话是如何进行的使用 Devise 身份验证 gem 进行管理.
For more information, I've written a Rails Devise Tutorial that shows how sessions are managed with the Devise authentication gem.
这篇关于“会话"从何而来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!