如何将用户与购物车链接?

时间:2011-09-02 22:16:50

标签: ruby-on-rails activerecord shopping-cart

我的应用有用户和购物车。

Theres目前没有用户和购物车之间的链接。

目前,无论用户是否登录,只有一个购物车可用,当添加产品时会创建current_cart,并在购物车付款时创建order_transaction(成功或失败)。如果成功,下次将产品添加到购物车时将创建新购物车。

如何将购物车与用户相关联,以便每位用户在添加产品时都为他们创建了新购物车?

application_controller

  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

路线

  get "log_in" => "sessions#new", :as => "log_in"
  get "log_out" => "sessions#destroy", :as => "log_out"
  get "sign_up" => "users#new", :as => "sign_up"

  get "cart" => "carts#show", :as => "current_cart"

  resources :orders
  resources :line_items
  resources :carts    
  resources :products
  resources :order_transactions

  resources :sessions
  resources :users

line_items_controller

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

感谢任何帮助,非常感谢!

1 个答案:

答案 0 :(得分:0)

最简单的方法是让用户拥有购物车

class User < ActiveRecord::Base
  has_one :cart

  def current_cart
    if self.cart.empty?
      self.cart.create!
    end
    self.cart
  end
end

class Cart < ActiveRecord::Base
  belongs_to :user

  def add_line_item(item)
    etc...
  end
end

class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def current_cart
    current_user.current_cart if current_user.present?
  end
end

我会推荐这个。这样,你只有 ONE 的东西来跟踪会话。您还应该尽量将“业务逻辑”DOWN移动到模型层,以便更容易测试。