该会话加载的力度如何? [英] How force that session is loaded?

查看:33
本文介绍了该会话加载的力度如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要使用会话 ID 信息的应用程序.我的会话存储在 cookie 中.我遇到的问题是,当用户第一次访问该站点时,控制器无法立即使用我的会话.我想我可能遗漏了一些关于如何在 Rails 中初始化会话的信息.但我对会话未加载这一事实持肯定态度,因为这是 session.inspect 的输出:

I'm working on an application that needs to use session id information. My session is stored in cookies. The problem I have is that my session is not immediately available to the controller when a user comes to the site for the first time. I think I may be missing something about how sessions are initialized in Rails. But I'm positve about the fact that the session is not loaded because this is the output of session.inspect:

#<Rack::Session::Abstract::SessionHash:0x15cb970 not yet loaded>

以下是如何使用 Rails 3.2.11ruby 1.9.3 重现问题:

Here is how to reproduce the problem with Rails 3.2.11 and ruby 1.9.3:

使用 test 控制器创建一个新应用程序:

Create a new application with a test controller:

rails new my_app
cd my_app/
rails g controller test
rm app/assets/javascripts/test.js.coffee
touch app/views/test/index.html.erb

尝试在该控制器中获取会话 ID:

Try to get the session id in that controller:

class TestController < ApplicationController
  def index
    puts session[:session_id]
    puts session.inspect
  end
end

添加需要的路由:

MyApp::Application.routes.draw do
  resources :test
end

然后访问应用程序并查看它的作用:

Then access the application and see what it does:

rails server

到:http://localhost:3000/test

这是控制台的输出:

#<Rack::Session::Abstract::SessionHash:0x3fd10f50eea0 not yet loaded>

然后http://localhost:3000/test,这次我们有一个会话:

Then again http://localhost:3000/test and this time we have a session:

400706c0b3d95a5a1e56521e455075ac
{"session_id"=>"400706c0b3d95a5a1e56521e455075ac", "_csrf_token"=>"Euaign8Ptpj/o/8/ucBFMgxGtiH7goKxkxeGctumyGQ="}

推荐答案

我找到了强制初始化会话的方法.访问会话显然不会强制初始化,但写入会话会强制初始化.我现在在控制器中做的是:

I found a way to force initialization of the session. Accessing the session apparently does not force initialization but writing into the session does. What I do in my controller is this now:

class MyController < ApplicationController
  protect_from_forgery
  def index
    session["init"] = true
    do_stuff
  end
end

我仍然不确定这是否应该被视为 Rails 中的正常行为.在我看来,必须写入会话以强制初始化是不正确的.阅读应该足够了.

Still I'm not sure if this should be considered normal behavior in Rails. It doesn't look right to me having to write into the session to force initialization. Reading should be enough.

这篇关于该会话加载的力度如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆