How can I get my shopping cart linked to a users session?
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.
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.
Its currently being created as such:
Application controller
class ApplicationController < 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
Line items controller
class LineItemsController < ApplicationController
def create
@product = Product.find(params[:product_id])
@line_item = LineItem.create!(:cart => current开发者_JS百科_cart, :product => @product, :quantity => 1, :unit_price => @product.price)
flash[:notice] = "Added #{@product.name} to cart."
redirect_to current_cart_url
end
end
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.
edit - Sessions controller
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 => "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 => "Logged out!"
end
Any help is very much appreciated!
The cart is tied to the session, so not all users will share it, it will be unique to the browser session it was created in - essentially one cart for every browser session created that visits your LineItemsController#create method.
This is typically done to allow a cart to be created before a user logs in or signs up, reducing the friction in actually adding items to a cart.
If you want to associate the cart with a user, then you could do this when they log in or sign up. If you've added the relation, then this should be as simple as:
current_cart.user = current_user
current_cart.save
精彩评论