2011-09-02 13 views
1

アプリにはユーザーとショッピングカートの両方があります。ユーザーをショッピングカートにリンクさせるにはどうすればよいですか?

現在、ユーザーとショッピングカートの間のリンクはありません。

ユーザーがログインしているかどうかにかかわらず、現在のカートは利用可能なカートが1つしかないため、商品が追加されたときにcurrent_cartが作成され、カートの支払い(成功または失敗) 。成功すると、次に商品をカートに追加するときに新しいカートが作成されます。

カートをユーザーとリンクするにはどうすればよいですか?製品を追加するときに各ユーザーに新しいカートが作成されますか?

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 

おかげどんなに助けても大丈夫です!

答えて

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だけです。また、 "ビジネスロジック"の多くをモデル階層に移動してテストしやすくする必要があります。

関連する問題