2013-05-28 28 views
1

我讀完這本書的敏捷web開發與軌道,任務四時,我感到非常困惑。如何使用:cart_id按會話查找當前購物車?

我知道基類中的current_cart方法可以通過會話找到目標購物車。但是,我不知道sysbol:card_id來自哪裏。

當lineItemController調用current_cart方法時,cart_id的值是什麼?

更重要的是,我已經運行了常見的「rails generate scaffold line_item product_id:integer cart_id integer」。這兩種cart_id有什麼關係?

class ApplicationController < ActionController::Base 
    protect_from_forgery 

    private 
    def current_cart 
     Cart.find(session[:cart_id]) 
    rescue ActiveRecord::RecordNotFound 
     cart = Cart.create 
     session[:cart_id] = cart.id 
     cart 
    end 
end 
+0

':card_id'只是一個關鍵;一個符號。類似於一個字符串。這只是在稍後的會話哈希中識別您的'cart.id'的一種方式。 – Sirupsen

回答

1

最初的session[:cart_id]值將是零所以Cart.find(session[:cart_id])會拋出錯誤,因此是得到執行救援塊的代碼。它做了三件事

1. Create a new Cart 
2. Save the id of newly created Cart in session 
3. return the newly created cart 

當同樣的方法被調用它會簡單地返回Cart.find(session[:cart_id])

0

車有很多line_items。購物車和line_items之間有一對多的關係。 因此,購物車ID將是line_items中的外鍵,即cart_id。

:cart_id包含cart_id的值。

因此,在current_cart方法中,您試圖查找id等於cart_id的購物車。

如果id = cart_id的卡片不存在,則會拋出錯誤,並在救援塊中創建新購物車並將其ID保存到會話[:cart_id]中並返回購物車。