【问题标题】:Keep session alive after closing browser.关闭浏览器后保持会话活动。
【发布时间】:2014-10-21 12:26:34
【问题描述】:

我该怎么做,在用户将某些东西添加到购物车后,并在重新打开 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 让这个会话保持活跃呢?

【问题讨论】:

  • 您需要保留会话 cookie,但这通常不是一个好主意。请改用基于 cookie 的技术。
  • @semir.babajic 如果我将 session[:cart_id] = cart.id 更改为 cookies[:cart_id] = cart.id,我会像以前一样拥有大部分功能吗?那我怎样才能恢复我的购物车呢?
  • 在您的数据库中保留一份购物车副本,并参考用户。

标签: ruby-on-rails ruby session cookies


【解决方案1】:

只需将cart_id 存储到cookies 中而不是会话中,您就会实现您想要的。当您需要提取购物车信息时,请使用 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

希望对你有帮助。

【讨论】:

  • 没错。请记住设置适当的 cookie 持续时间,您不希望它永远持续下去,也不要太短。
  • cookie[:..... 或 cookies[:... 对吗?还有我需要在 appcontroller 中写持续时间的地方吗?
  • cookies[:] 是对的,请参阅我更新的评论。这是您设置持续时间的方式:'cookies[:cart_id] = { :value => "XYZ", :expires => 5.hour.from_now }'
猜你喜欢
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 2012-04-11
  • 1970-01-01
  • 2014-11-02
  • 2011-02-23
相关资源
最近更新 更多