Ruby on Rails 4.0 session [cart_id] = nil

时间:2014-08-19 13:42:08

标签: ruby-on-rails-4 session-variables

在我学习RoR 4.0的过程中,我正在学习构建一个正在实现Cart的Rails项目的教程。我的问题是我不能在我的购物车上放置多个项目,因为当我返回主页面选择另一个项目时,我的购物车会更改其ID。我将cart_id存储在会话变量上,在我的应用程序控制器上的函数上: class ApplicationController<的ActionController :: Base的   protect_from_forgery

私有

def current_cart
  if session[cart_id].nil?              (*)
 puts “  ********************* “        (*)
     puts session[cart_id]              (*)
  end

  Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
  cart = Cart.create
  session[:cart_id] = cart.id
  cart
end

我从这个控制器调用此函数如下: class LineItemsController< ApplicationController的 def创建     @cart = current_cart     product = Product.find(params [:product_id])     @line_item = @ cart.line_items.build(:product => product)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to(@line_item.cart,
      :notice => 'Line item was successfully created.') }
    format.xml  { render :xml => @line_item,
      :status => :created, :location => @line_item }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @line_item.errors,
      :status => :unprocessable_entity }
  end
end

我做了几个睾丸,在我的current_cart中添加了标记为(*)的三行代码,我注意到每次在我的lineItems Controller上执行@cart = currect_cart时,session [cart_id]都是nil。 怎么会发生这种情况?能告诉我这个吗?

提前感谢您的帮助!

0 个答案:

没有答案