【问题标题】:Set start date and expiration date for Rails cookies设置 Rails cookie 的开始日期和到期日期
【发布时间】:2010-11-16 23:01:35
【问题描述】:

如何将 Rails cookie 设置为在特定日期开始和/或过期?

【问题讨论】:

    标签: ruby-on-rails cookies


    【解决方案1】:

    摘自Rails 5 documentation

    Cookie 是通过 ActionController#cookies 读取和写入的。

    正在读取的 cookie 是与请求一起收到的,正在写入的 cookie 将与响应一起发送出去。读取 cookie 并不会取回 cookie 对象本身,只会取回它所持有的值。

    写作示例:

    # Sets a simple session cookie.
    # This cookie will be deleted when the user's browser is closed.
    cookies[:user_name] = "david"
    
    # Sets a cookie that expires in 1 hour.
    cookies[:login] = { value: "XJ-122", expires: 1.hour }
    
    # Sets a cookie that expires at a specific time.
    cookies[:login] = { value: "XJ-122", expires: Time.utc(2020, 10, 15, 5) }
    
    # Sets a "permanent" cookie (which expires in 20 years from now).
    cookies.permanent[:login] = "XJ-122"
    

    [...]

    设置cookies的选项符号有:

    • :expires - 此 cookie 过期的时间,作为 Time 或 ActiveSupport::Duration 对象。

    [...]

    【讨论】:

    【解决方案2】:

    您的问题可能与以下问题有关: How to I dynamically set the expiry time for a cookie-based session in Rails

    其中一个 cmets 指向Deprecating SlideSessions:

    "..如果需要设置有效期 通过所有控制器的会话 在您的应用程序中,只需添加 您的以下选项 配置/初始化程序/session_store.rb 文件:

    :expire_after => 60.minutes
    

    如果需要设置不同的 过期时间不同 控制器或动作,使用 下面的代码在行动或一些 before_filter:

    request.session_options = request.session_options.dup
    request.session_options[:expire_after]= 5.minutes
    request.session_options.freeze
    

    只需要复制哈希 因为它已经被冻结了 点,即使修改 at 至少 :expire_after 是可能的并且 完美无瑕……”

    我希望这会有所帮助。 :)

    【讨论】:

    • ActiveRecord 会话存储也可以这样做吗?
    【解决方案3】:

    值得注意的是,目前无法为 cookie 设置开始时间。 cookie 集总是立即激活。

    【讨论】:

      猜你喜欢
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      相关资源
      最近更新 更多