【问题标题】:rails3 session storerails3 会话存储
【发布时间】:2010-08-26 22:01:00
【问题描述】:

请问您能告诉我 - 如何在 rails3 应用程序外部 Active Record 会话存储中使用?

在 rails2 中很简单

ActiveRecord::SessionStore::Session.establish_connection("sessions_#{RAILS_ENV}")

但是关于 rails3 吗?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-3


    【解决方案1】:

    查看config/initializers/session_store.rb

    注释掉关于使用:cookie_store的行

    取消注释底部关于使用:active_record_store的行

    # Use the database for sessions instead of the cookie-based default,
    # which shouldn't be used to store highly confidential information
    # (create the session table with "rails generate session_migration")
    MyApp::Application.config.session_store :active_record_store
    

    注意:“MyApp”将是您的应用程序的名称。

    【讨论】:

    • 谢谢,成功了。另外,rake db:sessions:create 和 rake db:migrate。
    【解决方案2】:

    查看activerecord-3.0.0.rc/lib/active_record/session_store.rb的来源我看到了:

    165     # The database connection, table name, and session id and data columns
    166     # are configurable class attributes.  Marshaling and unmarshaling
    167     # are implemented as class methods that you may override.
    
    183       # :singleton-method:
    184       # Use the ActiveRecord::Base.connection by default.
    185       cattr_accessor :connection
    
    208         def connection
    209           @@connection ||= ActiveRecord::Base.connection
    210         end
    

    所以,您应该可以执行以下操作:ActiveRecord::SessionStore::Session.connection = establish_connection("sessions_#{RAILS_ENV}"),但我还没有测试过。

    您还可以创建自己的会话类,您可以从同一个文件中更好地控制它如何连接到数据库:

     34   # You may provide your own session class implementation, whether a
     35   # feature-packed Active Record or a bare-metal high-performance SQL
     36   # store, by setting
     37   #
     38   #   ActiveRecord::SessionStore.session_class = MySessionClass
     39   #
     40   # You must implement these methods:
     41   #
     42   #   self.find_by_session_id(session_id)
     43   #   initialize(hash_of_session_id_and_data)
     44   #   attr_reader :session_id
     45   #   attr_accessor :data
     46   #   save
     47   #   destroy
    

    【讨论】:

    • 正确的代码是 ActiveRecord::SessionStore::Session.establish_connection("sessions_#{Rails.env}") 非常感谢!!!
    【解决方案3】:

    你必须使用它。

    Rails.application.config.session_store :active_record_store
    

    我不确定如何设置表名。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 2011-06-03
    • 2011-10-03
    • 2017-06-08
    • 1970-01-01
    相关资源
    最近更新 更多