适当数量到购物车

时间:2014-08-16 22:17:56

标签: ruby-on-rails ruby

在我的商品详情中添加了数量的文字字段。无论我在文本字段中输入的数字如何,购物车将仅显示该点击的增量。当然,我还没有告诉它除此之外什么都不做。但是,我该怎么办?我无法在任何地方找到解决方案。

这是我的购物车添加方法:

 def add_product(product_id)
    line_items.find_or_initialize_by(product_id: product_id).increment(:quantity)
  end

并在LineItems中#create:

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

如果有任何其他相关代码我可以附上,请告诉我。感谢。

查看代码

<%= image_tag(product.image.url, class: 'prodli-img') %>
      <h3><%= product.name %></h3>
      <p><%= product.description %></p>
      <span class="price"><%= number_to_currency(product.price) %></span>
      <!--<p> <%= product.colors %> </p>-->
      <div id= "text_field"><%= text_field_tag 'quantity' %> </div>
      <%= button_to 'Add to Cart', line_items_path(:product_id => product) %>
  <% end %>

LI创建

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


  respond_to do |format| 
    if @line_item.save
       format.html { redirect_to "/#products", notice: "Product added to cart!" }
       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
  end

2 个答案:

答案 0 :(得分:1)

Quantity是@line_item对象的一个​​属性。

所以你应该这样做

@line_item.quantity = params[:quantity]

当您保存@line_item时,它将存储新值。

答案 1 :(得分:1)

您无法使用“button_to”

轻松传递其他参数

这应该效果更好

      <h3><%= product.name %></h3>
      <p><%= product.description %></p>
      <span class="price"><%= number_to_currency(product.price) %></span>
      <%= form_for :line_item, url: product_line_items_path(product) do |f| %>
      <%= f.text_field 'quantity' %>
      <%= f.submit 'Add to Cart' %>
      <% end %>

你创建方法中的params看起来就像......

=> {"utf8"=>"V",
 "authenticity_token"=>"blah blah"
 "line_item"=>{"quantity"=>"12"},
 "commit"=>"Add to Cart",
 "action"=>"create",
 "controller"=>"line_items",
 "product_id"=>"1"}

因此您可以使用...

检索数量
@line_item.quantity = params[:line_item][:quantity]