2013-01-10 78 views
0

我该怎么办时,该用户之后添加的东西到购物车,离开后重新打开浏览器(关闭)轨恢复它的会话,用户可以购买更多... 现在我有这样的关闭浏览器后保持会话生效。

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保持这个会话活着?

+1

您需要保留会话cookie,但这通常不是一个好主意。改为使用基于cookies的技术。 –

+0

@ semir.babajic我会像以前一样拥有大部分功能,如果我将会话[:cart_id] = cart.id更改为cookie [:cart_id] = cart.id?那我怎么能恢复我的购物车? – brabertaser19

+0

在您的数据库中保存购物车的副本并提供给用户。 – MiniRagnarok

回答

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 

希望它有帮助。

+0

因为我现在用会话,但与cookie,对吗? – brabertaser19

+0

正是。请记住设置适当的Cookie时间,您不希望它永远持续下去,也不要太短。 –

+0

cookie [:.....或cookies [:...是对的?另外我需要在appcontroller中写入持续时间? – brabertaser19

相关问题