2011-09-10 30 views
3

我超級新編程,我試圖讓我的應用程序中鏈接到用戶會話的購物車。所以每個用戶都可以擁有自己的購物車,並且沒有人可以查看其他人的購物車。如何將購物車鏈接到用戶會話?

感謝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 

任何幫助是非常感謝!

回答

3

購物車與會話綁定,因此並非所有用戶都會共享它,它對於創建的瀏覽器會話來說是唯一的 - 基本上每個瀏覽器會話創建一個訪問LineItemsController#create方法的購物車。

這通常用於在用戶登錄或註冊之前創建購物車,從而減少實際向購物車添加物品時的摩擦。

如果您想將購物車與用戶相關聯,那麼您可以在登錄或註冊時執行此操作。如果你已經添加了關係,那麼這應該是如此簡單:

current_cart.user = current_user 
current_cart.save 
+0

太棒了,謝謝!購物車被設置的用戶的user_id保存,但如果在同一瀏覽器會話中登錄(購物車的user_id字段被更新爲添加了某個內容的最後一個用戶),它仍然可供其他用戶使用。有沒有辦法結束會話,因此在註銷時刪除購物車? **編輯** - 將current_cart.delete添加到會話銷燬方法會在重新登錄時出現'找不到id = 8的購物車'。 – Dave

+0

當您使用用戶ID更新購物車時,請將其從會話中刪除。您還需要在current_cart方法中創建新的會話購物車之前,有條件地獲取用戶分配的購物車。 – Codebeef