我在页面上显示产品列表,在每个产品旁边都有一个复选框。
现在,当用户提交表单时,我需要获取产品ID,然后将这些产品添加到购物车中。
每个复选框都如下:
<input type=checkbox value=39827 ... />
是否有一种很酷的获取所有ID的方式,或者我必须在处理帖子的操作方法中执行此操作:
def add_products_to_cart
@products = Product.find_....
@products.each do |p|
// check if checkbox form key exists, if it is selected, add to cart
end
end
注意:上面的模式就是我在其他框架中所做的,我很好奇是否有 Rails Way 来做这件事。
答案 0 :(得分:1)
您可以执行以下操作:
# view
# somethings like this (HAML):
- products.each do |product|
= check_box_tag 'product_ids[]', product.id, false
# Usage: check_box_tag(name, value = '1', checked = false, options = {})
# which generate this kind of HTML:
<input type="checkbox" value="39827" name="product_ids[]" />
然后在控制器中:
# controller's action receiving the params after submitting the form
def add_products_to_cart
# here params[:product_ids] should contain an array of ids, the checked ones
@products = Product.where(id: params[:product_ids])
@products.each do |product|
# your logic to add a product in your cart, something like
if current_user.can_access?(product) # logic to prevent User from adding forbidden products
my_cart << product
end
end
end
希望这有帮助!
如果需要,请随时提出任何问题!