开发者

How to store data from session to DB in RoR?

I have a shopping Cart that contai开发者_如何学编程ns many cart item and price or the order. It remember the users choose in the cart, but does not store into database yet. What should I do to store these records.

Cart have many cart item. One cart item contain the number of product, and the product obj.


You should keep cookies as small as possible because:

  1. Browsers need to send cookies to your server on every request (big cookie = slower site).
  2. There is a (practical/approximate) 4 KB size limit for cookies.

Hence, the best design is to store only the IDs of the relevant objects in the session. In your case you should need only the cart ID and the user ID. Create database-backed ActiveRecord models for everything (if you don't have them already), and load the current objects on every request with controller before filters, like this:

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


I don't recommend that really, but u still can do with

config.action_controller.session_store = :active_record_store

in config/environment.yaml

Then just store the object in the session:

# 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜