Answer the question
In order to leave comments, you need to log in
How to save multiple entries on one form in rails?
It is necessary to save several records on one form, now only one is saved. I don't understand why.
<%= 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 %>
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
Answer the question
In order to leave comments, you need to log in
After 4 hours of torment, I did it this way, I don’t know if it’s right ... but everything is saved as it should be , the
controller
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
redirect_to :back
end
<%= 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 %>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question