Set start date and expiration date for Rails cookies

后端 未结 3 734
故里飘歌
故里飘歌 2020-11-27 10:14

How do I set a Rails cookie to start and/or expire at a certain date?

3条回答
  •  感动是毒
    2020-11-27 11:04

    Excerpts from Rails 5 documentation:

    Cookies are read and written through ActionController#cookies.

    The cookies being read are the ones received along with the request, the cookies being written will be sent out with the response. Reading a cookie does not get the cookie object itself back, just the value it holds.

    Examples of writing:

    # 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"
    

    [...]

    The option symbols for setting cookies are:

    • :expires - The time at which this cookie expires, as a Time or ActiveSupport::Duration object.

    [...]

提交回复
热议问题