0

我该怎么做,在用户添加一些东西到购物车,并在重新打开 rails 后离开浏览器(关闭)恢复它的会话,用户可以购物更多......现在我有这样的

class ApplicationController < ActionController::Base
  protect_from_forgery

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


end

并在下订单后销毁:

def destroy
    @cart = current_cart
    @cart.destroy
    session[:cart_id] = nil
    respond_to do |format|
      format.html { redirect_to session[:prev_url],
        :notice => I18n.t(:empty_card) }
      format.json { head :ok }
    end
  end

但是我怎样才能告诉 RoR 让这个会话保持活跃呢?

4

1 回答 1

2

只需存储cart_id到 cookie 中而不是会话中,您就会实现您想要的。当您需要提取购物车信息时,请使用 cookie 中的 ID。

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :current_cart 
  private
    def current_cart
      Cart.find(cookies[:cart_id])
      @cart = Cart.find(cookies[:cart_id])
      rescue ActiveRecord::RecordNotFound
      cart = Cart.create
      cookies[:cart_id] = cart.id
      cart
    end


end

希望能帮助到你。

于 2013-01-10T20:29:42.410 回答