2010-01-04 69 views
1

我有一個購物車,其中包含許多購物車項目和價格或訂單。它記得用戶在購物車中選擇,但尚未存儲到數據庫中。我應該怎麼做才能存儲這些記錄。如何在RoR中將會話中的數據存儲到數據庫?

購物車有很多購物車項目。一個購物車項目包含產品編號和產品目標。

回答

1

你應該保持餅乾儘可能小,因爲:

  1. 瀏覽器需要發送cookie到您的服務器上的每個請求(大餅乾=網站慢)。
  2. Cookie有一個(實際/近似)4 KB的大小限制。

因此,最好的設計是隻存儲會話中相關對象的ID。在你的情況下,你應該只需要購物車ID和用戶ID。一切創建數據庫支持ActiveRecord的模型(如果沒有他們的話),以及前置過濾器在每個請求與控制器加載當前對象,像這樣:

class ApplicationController < ActionController::Base 
    before_filter :load_current_user 

    private 
    def load_current_user 
    @current_user = User.find_by_id(session[:user_id]) 
    end 
end 
1

我不建議真的,但你仍然可以

config.action_controller.session_store = :active_record_store 
在配置

/environment.yaml做

然後,只需存儲在會話對象:

# Note: 
# do whatever u want but make sure you save the objects before you store them in the session object. 
session[:cart] = @cart 
# or you can modify them but don't forget to save the object. 
session[:cart].something = 'blabla' 
session[:cart].save 
相關問題