新手问题 关于 rails 更智能的购物车问题

zerzerheart · 2015年11月26日 · 最后由 zerzerheart 回复于 2015年11月26日 · 2765 次阅读

楼主大三狗,在自学 rails,跟着 web 开发敏捷之道第四版学习,ruby 的版本是 2.0.0p643,rails 的版本是 4.2.4,跟着书上的步骤做到了更智能的购物车这里,但是购物车商品的数量显示却总是停留在 1,点击 Add to Cart 后不会生成重复的在线商品,但是不管点几次,数量却总是 1,对照代码,和书上并没有不同,求大神帮忙。下面是代码 Cart.rb:

def add_product(product_id)
   current_item = line_items.find_by_product_id(product_id)
   if current_item
     current_item.quantity += 1
   else
     current_item = line_items.build(product_id: product_id)
   end
   current_item
 end

line_items_controller.rb:

def create
   @cart = current_cart
   product = Product.find(params[:product_id])
   @line_item = @cart.add_product(product.id)

  respond_to do |format|
     if @cart.save
       format.html { redirect_to @line_item.cart,notice: 'Line item was successfully created.' }
       format.json { render :show, status: :created, location: @line_item }
     else
       format.html { render :new }
       format.json { render json: @line_item.errors, status: :unprocessable_entity }
     end
    end
 end

store.html.erb:

<% if notice %>
  <p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% @products.each do |product| %>
  <div class="entry">
  <%= image_tag(product.image_url) %>
  <h3><%= product.title %></h3>
  <%= sanitize(product.description) %>
  <div class="price_line">
    <span class="price"><%= number_to_currency(product.price) %></span>
    <%= button_to 'Add to Cart',line_items_path(:product_id => product) %>
  </div>
</div>
<% end %>

application_controller.rb

def current_cart
  Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
  cart = Cart.create
  session[:cart_id] = cart.id
  cart
end
current_item.quantity += 1

你这里给这个 current_item 的 quantity 加 1 后,没有 save

#1 楼 @stone 哇!好神奇!谢谢你啦:)

需要 登录 后方可回复, 如果你还没有账号请 注册新账号