Reputation:
I need to save many items to Cart on form, user enter quantity one form, and selected items goes to db, but now save only first entered quantity of item. Why?
my form
<%= form_for @cart_item do |f| %>
<% @category.items.each do |item| %>
<%= item.name %>
<%= f.hidden_field :item_id, :value => item.id %>
<%= f.text_field :qty %>
<% end %>
<%= f.submit %>
<% end %>
And controller cart_items_controller.rb
class CartItemsController < ApplicationController
before_action :set_cart, only: [:create]
def create
@cart_items = CartItem.create(cart_items_params)
@cart_items.cart_id = @cart.id
if @cart_items.save
redirect_to :back
else
render root_path
end
end
private
def cart_items_params
params.require(:cart_item).permit(:id, :qty, :item_id, :cart_id)
end
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
Upvotes: 0
Views: 301
Reputation:
I do this:
def create
@cart_items = params[:cart_items]
@cart_items.each do |c|
@cart_item = CartItem.new(c)
if @cart_item.qty.present?
@cart_item.cart_id = @cart.id
@cart_item.save
end
end
and form
<%= form_tag cart_items_path do %>
<% @cart_items.each do |cart_item| %>
<%= fields_for "cart_items[]", cart_item do |f| %>
<% @category.items.each do |item| %>
<%= item.name %>
<%= f.hidden_field :item_id, value: item.id %>
<%= f.text_field :qty %>
<% end %>
<%= f.submit %>
<% end %>
<% end %>
<% end %>
Upvotes: 0
Reputation: 35360
There are a few problems here. I'll give you a little bump:
<% @category.items.each do |item| %>
<%= item.name %>
<%= f.hidden_field :item_id, :value => item.id %>
<%= f.text_field :qty %>
<% end %>
For each CartItem
, this is going to create an input like this
<input name="qty">
This is problematic because only one (the last one in the DOM) will be submitted. You need to research fields_for
and incorporate that into your loop in order to get unique names for each Item
in the form.
This same issue follows through into your controller
def cart_items_params
params.require(:cart_item).permit(:id, :qty, :item_id, :cart_id)
end
This is going to look for a single :id
, :qty
, :item_id
, and :cart_id
, when in reality you're looking to accept multiple :item_id
and :qty
fields. You need to research Strong Parameters with nested has_many associations.
Finally you have this
@cart_items = CartItem.create(cart_items_params)
which is going to attempt to create a single CartItem
when you're really trying to create multiple items and associate them back to the Cart
. You need to research accepts_nested_attributes_for
as well as more generally "rails form save has_many
association". It's a widely covered topic here on SO and elsewhere.
Upvotes: 1