Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I link a user with a shopping cart?
    primarykey
    data
    text
    <p>My app has both users and a shopping cart.</p> <p>Theres currently no link between users and shopping carts. </p> <p>At the moment regardless of if a user is logged in or not there is only one shopping cart available, the current_cart is created when a product is added and an order_transaction is created when the cart is paid for (success or fail). If successful, a new cart will be created the next time a product is added to the cart.</p> <p>How can I link a cart with a user, so each user has a new cart created for them when adding a product?</p> <p><b>application_controller</b></p> <pre><code> 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 </code></pre> <p><b>routes</b> </p> <pre><code> get "log_in" =&gt; "sessions#new", :as =&gt; "log_in" get "log_out" =&gt; "sessions#destroy", :as =&gt; "log_out" get "sign_up" =&gt; "users#new", :as =&gt; "sign_up" get "cart" =&gt; "carts#show", :as =&gt; "current_cart" resources :orders resources :line_items resources :carts resources :products resources :order_transactions resources :sessions resources :users </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>Thanks for any help its much appreciated!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload