Difference between session[:food] and cookies.permanent[:food]

前端 未结 2 1758
暖寄归人
暖寄归人 2021-02-09 15:22

which are the difference between session[:food]=\"pizza\" and cookies.permanent[:food]=pizza?
I tried to read rails documentation and it says:

2条回答
  •  无人共我
    2021-02-09 15:46

    if you do session[:food] you are using a traditional Rails session : this session object makes your value "pizza" available from page to page by storing it in a cookie that expires upon browser close ( which means if you close your browser, your session[:food] will be destroyed )

    When we talk about permanent we talk about persistent sessions, so what means ?

    persistent session is a permanent cookie that still exist ("forever") even if you close the browser, and don't expires only if you explicitly expire it or remove it .

    but how to make a cookie that still exist "forever" ?

    if i say "forever" it's because this is a tricky and the way to do this is to set a cookie expires for a long long time like 20 years from now or 60 years .... like this :

    cookies[:remember token] = { value: "pizza", expires: 20.years.from now.utc }
    

    This pattern of setting a cookie that expires 20 years in the future became so common that Rails added a special permanent method to implement it, so that we can simply write :

    cookies.permanent[:food] = "pizza"
    

    to answer your question, there is no difference in structure, each one is a cookie, but difference is only in the lifetime of each one

    hope this help you

提交回复
热议问题