Search code examples
ruby-on-railsrubysessionsession-variablesshopping-cart

How can I save line_items from a shopping cart only in session?


I'm new in ruby ​​on rails, I'm making a shopping cart, where is not necessary log in to add products to the shopping cart and is not necessary log in for buy the products in the shopping cart, for that reason I don’t have to keep the shopping cart in the database, I need to save the shopping cart in session, a shopping cart has many line_items and each line_item has a product, , another case is when the user is log in, in this case I have to store the shopping cart in database, this part is working, but what i need is to add the shopping cart with many line_items to session because the user is log out, I search but cant find anything useful, I appreciate any help, any idea, any link to solve my problem. Thanks

Excuse my English is not my native language


Solution

  • Rails gives you the ability to store information in the session hash. I would recommend adding a key to the session hash to store an array of line items. I would put something like this in your controller, or the application controller like this example:

    class ApplicationController < ActionController::Base
      before_filter :build_temporary_cart
    
      def build_temporary_cart
        # This assumes that you check for logged in user using current_user
        session[:temporary_shopping_cart] = [] unless current_user
      end
    end
    

    When your guest user clicks add to cart, you'd do something like this in your line items controller or whatever controller you are using for adding items to shopping carts:

    session[:temporary_shopping_cart] << @line_item
    

    Check out http://guides.rubyonrails.org/action_controller_overview.html#accessing-the-session for more information on accessing the session hash.