I have an Order
and Items
, with join table OrderItems
that act as line items in an order. In order#show
, I want to display all instances of Items
and be able to add this to the order through creating a new OrderItem
. The issue is that when I post the form, order_item#create
makes 40 new order_items
for all Items
, instead of just creating one instance of OrderItem
for that one item I want to add.
Here is the OrderItems
controller:
def create
@order_item = @order.order_items.build(order_item_params)
if @order_item.save
flash[:notice] = "Your item was added"
redirect_to [@user, @order]
else
flash[:error] = "Your item was not added. Please try again."
redirect_to [@user, @order]
end
end
Here is the form in order#show
<% @items.each do |item| %>
<div>
<%= form_for [@user, @order, @order.order_items.create(:item_id => item.id)] do |f| %>
<div class="form-group">
<%= f.label item.name %>
<%= f.label "$#{item.price.to_s}" %>
</div>
<div class="form-group">
<%= f.label 'quantity' %>
<%= f.text_area :quantity %>
</div>
<div class="form-group">
<%= f.label 'item id' %>
<%= f.text_area :item_id %>
</div>
<div class="form-group">
<%= f.submit 'Add Item', class: 'btn' %>
</div>
<% end %>
</div>
<% end %>
Actually, the order_item#create
action isn't creating the 40 order_items
. It's your form:
<%= form_for [@user, @order, @order.order_items.create(:item_id => item.id)] do |f| %>
Change the create
to build
and that way it won't save the 40 instances. It will only save the one you hit submit for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.