如何将我的购物车链接到用户会话?

时间:2011-09-10 19:18:42

标签: ruby-on-rails session e-commerce shopping-cart

我是编程的新手,我正在尝试在我的应用中使用与用户会话相关联的购物车。因此,每个用户都可以拥有自己的购物车,没有人可以查看其他人的购物车。

我有一个工作车,感谢Railscasts,但它目前正在自己​​的会话中创建。因此,如果您以不同的用户身份登录并不重要,那么只有一个推车正在使用,所有用户都会共享它。

目前正在创建:

应用程序控制器

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

订单项控制器

class LineItemsController < ApplicationController
  def create
    @product = Product.find(params[:product_id])
    @line_item = LineItem.create!(:cart => current_cart, :product => @product, :quantity => 1, :unit_price => @product.price)
    flash[:notice] = "Added #{@product.name} to cart."
    redirect_to current_cart_url
  end
end

我已经将user_id添加到购物车模型并将用户has_one购物车和购物车设置为用户,但我无法确定购物车创建方式需要更改的内容工作。

编辑 - 会话控制器

  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

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

购物车与会话绑定,因此并非所有用户都会共享它,它对于创建它的浏览器会话来说是唯一的 - 实际上每个浏览器会话都会有一个购物车访问您的LineItemsController #create方法。

这通常是为了允许在用户登录或注册之前创建购物车,从而减少实际将商品添加到购物车时的摩擦。

如果您想将购物车与用户相关联,那么您可以在登录或注册时执行此操作。如果你已经添加了关系,那么这应该简单如下:

current_cart.user = current_user
current_cart.save