【发布时间】:2014-06-13 04:50:50
【问题描述】:
我正在建立一个 RoR 定制商店,我只是想添加一些花里胡哨的东西。我有我的产品模型,其中 product#index 作为我商店的根...每个产品都有一个添加到购物车按钮。当您单击添加到购物车时,将使用数量 (1) 创建一个 line_item。看起来像这样。
<% @products.each do |product| %>
<%= link_to "#{product.title}", :action => 'show', :id => product %>
<%= link_to(image_tag("#{product.image_url}", :size => "200x200"), product) %>
<%= truncate product.description, length: 180 %> <%= link_to "read more", product %>
<%= button_to 'Add to Cart', line_items_path(:product_id=> product), class: "btn btn-primary" %>
<% end %>
我想添加一个数量选择框。在上面的代码中,我没有使用 form_for 或 simple_form_for。为了向创建的 line_item 添加数量,我必须使用 form_for(对吗?)所以我添加了
<%= simple_form_for(@line_item) do |f| %>
<%= f.select :quantity, [1, 2, 3] %>
<%= f.button :submit, 'Add to Cart', line_items_path(:product_id=> product), class: "btn btn-primary" %>
<% end %>
更新
<%= simple_form_for(@line_item, url:line_items_path(product_id:product)) do |f| %>
消除了参数错误...我现在的问题是数量没有更新...我知道为什么,但不确定如何解决。
这是根据提交按钮创建 line_item 时的控制器:
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
...
end
add_product 方法只是添加一个。我在我的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
我应该废弃方法并将数量 = 声明为表单值吗?我有点生疏了。
【问题讨论】:
标签: ruby-on-rails ruby