0

我需要做购物车,但是为什么当我第一次去页面时,我没有看到@cart 对象,但如果刷新,一切都好。如果简单地说:购物车不是在第一页加载时创建的,而是在第二个页面加载时创建的,这很糟糕.... 怎么办,当我在页面的浏览器 url 中打开时,我立即看到购物车对象?

我的代码:(app_controller)

  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

并查看:

%li
              = link_to "Перейти в корзину", @cart

但是如何在页面打开时创建购物车对象......而不是当我在页面上时,完成某事......

4

2 回答 2

1

简单地说,在救援块中(当购物车尚未在数据库中时),您需要将新创建的购物车分配给实例变量@cart,而不是局部变量cart

before_filter :current_cart 

private

def current_cart
  @cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
  @cart = Cart.create
  session[:cart_id] = @cart.id
  @cart
end
于 2013-02-14T22:27:07.773 回答
1

尝试这个:

 before_filter :current_cart 
private
    def current_cart
      @cart = Cart.where(id: session[:cart_id]).first #this will return nil if the Cart with id session[:cart_id] does not exist
      @cart = Cart.create if @cart.nil?
      session[:cart_id] = @cart.id
      @cart
    end
于 2013-02-14T22:28:36.913 回答