title: How can I get my shopping cart linked to a users session?
body: <p>Im super new to programming and I'm trying to get a shopping cart working in my app which is linked to user sessions. So each user can have their own shopping cart and no one can view anyone else's cart. </p>
  
  <p>I have a working cart thanks to Railscasts but its currently being created in its own session. So it doesn't matter if you log in as different users, there is only ever one cart in use and all user share it.</p>
  
  <p>Its currently being created as such:</p>
  
  <p><b>Application controller</b></p>
  
  <pre><code>class ApplicationController &lt; ActionController::Base
    helper :all # include all helpers, all the time
    protect_from_forgery # See ActionController::RequestForgeryProtection for details
    helper_method :current_user
    helper_method :current_cart
  
    def current_user
      @current_user ||= User.find(session[:user_id]) if session[:user_id]
    end
  
    def current_cart
      if session[:cart_id]
        @current_cart ||= Cart.find(session[:cart_id])
        session[:cart_id] = nil if @current_cart.purchased_at
      end
      if session[:cart_id].nil?
        @current_cart = Cart.create!
        session[:cart_id] = @current_cart.id
      end
      @current_cart
    end
  end
  </code></pre>
  
  <p><b>Line items controller</b></p>
  
  <pre><code>class LineItemsController &lt; ApplicationController
    def create
      @product = Product.find(params[:product_id])
      @line_item = LineItem.create!(:cart =&gt; current_cart, :product =&gt; @product, :quantity =&gt; 1, :unit_price =&gt; @product.price)
      flash[:notice] = "Added #{@product.name} to cart."
      redirect_to current_cart_url
    end
  end
  </code></pre>
  
  <p>I've got as far as adding a user_id to the cart model and setting user has_one cart and a cart belong_to a user but I can't figure out what needs to change in the way a cart is created to actually get it to work.</p>
  
  <p><b>edit - Sessions controller</b></p>
  
  <pre><code>  def create
      user = User.authenticate(params[:username], params[:password])
      if user
        session[:user_id] = user.id
        current_cart.user = current_user
        current_cart.save
        redirect_to root_path, :notice =&gt; "Welcome back!"
      else
        flash.now.alert = "Invalid email or password"
        render "new"
      end
    end
  
    def destroy
      session[:user_id] = nil
      redirect_to root_path, :notice =&gt; "Logged out!"
    end
  </code></pre>
  
  <p>Any help is very much appreciated!</p>