D
D
dexdev2014-12-02 20:20:04
Ruby on Rails
dexdev, 2014-12-02 20:20:04

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

That's what the user would indicate the number of qty on the form, and only the selected one left, now only id 2 goes to the database, although I indicate the number of both id 1 and id 2.
Please help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dexdev, 2014-12-06
@AdilA

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

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 %>

S
Sergey Krasnodemsky, 2014-12-02
@Prognosticator

Tyk
Tyk

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question