Rails v2.3 : Difference between session and cookies

后端 未结 4 926
野趣味
野趣味 2020-12-31 04:58

I am learning Rails by reading the online guide(for Rails v2.3). The guide is great, however, there is a confusion for me, that\'s:

there is a chapt

4条回答
  •  抹茶落季
    2020-12-31 05:48

    A cookie is a small text file stored in the browser.

    A session is the concept of a state of being "in-use", and that state can have data associated with it. Rails keeps track of sessions with cookies, and lets you choose different storage for associated data and access it with the same session interface.

    CookieStore means all the session information is stored inside the cookie itself. You can choose to use various other stores where appropriate, and it'll still be available with your session accessor methods.

    In addition to the session, you can set other cookies to store information on the user's browser. These are not tied to the session and can be set, accessed and deleted independently.

    Example 1, storing a logged-in user's shopping cart in a session:

    session[:embarassing_products] = ['ooh',
                                      'naughty',
                                      'lucky_im_using_activerecord_store',
                                      'only_the_session_id_is_in_the_cookie',
                                      'other_data_arent_in_the_browser']
    

    The shopping cart is preserved for the user's session. You can set the session to end when the browser window is closed, when the user logs out, or when a certain amount of time passes.

    Example 2, remembering a browser's last language preference for your domain in a cookie:

    cookie[:lang] = 'en-US'
    

    This information is stored inside the cookie itself. Unless the cookie expires or is deleted (by you or the user), it stays inside the browser.

提交回复
热议问题