Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sessions, Cookies and Flash in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.11k
    Comment on it

    Sessions, Cookies and Flash in Rails

    In rails if we want to store data for multiple request there are majorly three kinds of mechanism can be used for different different purposes. 

    Flash:

    Flash stores the data only until the new request. So it gets expired as soon as the request goes to the new request. It is simply used for displaying messages notices etc. For example if after successfully signing up user is redirected to homepage then the flash message can be shown in the homepage that user is successfully signed in.
     

    # Storing value in flash variable:
    
    flash[:notice] = "User is successfully signed in"
    
    # Retriveing in view
    
    <% flash[:notice] %>


    Sessions:

    Sessions store data during a complete session. Sessions are most commonly used for storing user information for authenticating the user for the next time. Suppose you are creating a shopping site, you can store the cart_id in the session so that whenever you want you can retrieve your cart.

    # Storing cart id in session
    
    session[:cart_id] = "CART ID"
    
    # Retrieving cart using session
    
    cart = Cart.find(session[:cart_id])
    
    # You can also disable the session using 
    
    session :off 
    
    # It accepts only, except and proc, lambda for specifying conditions for different types of actions.

    For more details about you can go through the following link.

    Session Management in Rails

    Cookies:

    Cookies can store information for a much longer time, have you ever noticed why you ever logged in facebook even if you come after two days. It is because some of your information gets stored in the browser cookies. You can also set expiry time during creation of cookie

    # To set cookie
    
    cookie[:user_token] = "USER TOKEN"
    
    # Setting cookie with expiry
    
    cookie[:user_token] = {value: "USER TOKEN", :expires => Time.now + 7200}
    
    # Reading Cookie
    
    cookie[:user_token] 
    # => "USER TOKEN"
    
    # Deleting Cookie
    
    cookies.delete :user_token

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: