这是一家网上商店
我使用嵌套的size_attributes创建产品
客户可以购买产品,并且必须选择尺寸
products_controller.rb
def params_product
params.require(:product).permit(:title, :description, :price,
:category_id, :color, sizes_attributes: [:id, :size_name, :quantity, :_destroy])
end
products / show.html.erb
因此客户可以选择所需的数量和尺寸
<%= form_tag order_items_path do %>
<%= hidden_field_tag :product_id, @product.id %>
<%= hidden_field_tag :user_id, current_user.id %>
<%= number_field_tag :quantity, 1 %>
<%= collection_select :size, :id, @product.sizes, :id, :size_name, prompt: "Votre taille" %>
<%= submit_tag "Add to Cart" %>
<% end %>
shopping_cart.rb
def initialize(token:)
@token = token
end
def order
@order ||= Order.find_or_create_by(token: @token, status: 0) do |order|
order.sub_total = 0
end
end
def add_item(product_id:, quantity: 1, user_id:, size_id:)
@product = Product.find(product_id)
@size = Size.find_by(id: size_id)
#binding.pry
user = User.find(user_id)
order.user_id = user.id
order_item = order.items.find_or_initialize_by(product_id: product_id)
order_item.price = @product.price
order_item.quantity = quantity
order_item.size_id = @size.id
ActiveRecord::Base.transaction do
order_item.save
end
end
order_items_controller.rb
def create
current_cart.add_item(
product_id: params[:product_id],
quantity: params[:quantity],
user_id: params[:user_id],
size_id: params[:size_id]
)
end
它记录“ S” ...
答案 0 :(得分:1)
collection_select
生成一个名称为name =“ size [id]”的选择字段,您将在控制器参数中得到{size: {id 1}}
而不是{size_id: 1}
。您需要的是select_tag帮助器:
<%= select_tag :size_id, options_from_collection_for_select(@product.sizes, :id, :size_name), prompt: "Votre taille" %>