我正在尝试为在线商店创建购物车。在产品页面上有一个“添加到购物车”按钮,单击它会创建line_item并添加到cart.
我想这样做,以便在同一页面上,在按钮旁边,我可以分别选择要添加到的产品数量,line_item然后选择添加到cart。
控制器代码
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create]
def new
@line_item = LineItem.new
end
def create
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product)
@line_item.quantity = params['q'].to_i
if @line_item.save
redirect_to @line_item.cart, notice: 'Item added to cart.'
else
render :new
end
end
private
def line_item_params
params.require(:line_item).permit(:product_id, :quantity)
end
end
查看代码 view/products/show.html.erb
<section class="section instrument-show">
<div class="columns">
<div class="column is-8">
<h1 class="title is-2"><%= @product.title %></h1>
<h3 class="subtitle is-4">Description</h3>
<%= @product.description %>
</div>
<div class="column is-3 is-offset-1">
<div class="bg-white pa4 border-radius-3">
<h4 class="title is-5 has-text-centered"><%= number_to_currency(@product.price) %></h4>
<form>
<input type="number" name="q" min="1" max="50" step="1" class="input label">
</form>
<%= button_to 'Add to cart', line_items_path(product_id: @product), class: 'button is-warning add-to-cart' %>
</div>
</div>
</div>
</section>
在控制器中使用此版本的代码,params['q']我得到“nil”,然后是.to_i- 零。为什么要形成
<form>
<input type="number" name="q" min="1" max="50" step="1" class="input label">
</form>
不将此参数传递给控制器?
有人可以告诉我如何LineItemsController获取产品页面上输入的数字(购买产品的数量)。
add_product 方法
def add_product(product)
current_item = line_items.find_by(product_id: product.id)
if current_item
current_item.increment(:quantity)
else
current_item = line_items.build(product_id: product.id)
end
current_item
end