D
D
dexdev2014-11-28 14:09:57
Ruby on Rails
dexdev, 2014-11-28 14:09:57

How to add form data to linked hbtm table?

Good day, I can’t figure out how to make a form, the situation is as follows. There is a basket, you need to add goods there, but the task is not with the “Add to cart” button, but immediately with the number of goods.
Created a Cart model

class Cart < ActiveRecord::Base
  has_and_belongs_to_many :items
end

item model
class Item < ActiveRecord::Base
  belongs_to :category
  has_and_belongs_to_many :carts
end

and table CartsItem
class CreateCartsItem < ActiveRecord::Migration
  def change
    create_table :carts_items, id: false do |t|
      t.integer :cart_id
      t.integer :item_id
      add_column :carts_items, :quantity, :decimal
    end
  end
end

Now I am making a form and I can’t understand how to create a Cart on the form right away and send everything that is indicated in the form with the specified quantity to carts_items, please tell me how to do this
<%= form_for @cart do |f| %>
<% @category.items.each do |item| %>
<ul class="categories-ul clear">
  <li>
    <div class="form-div">
      <div class="item-name left">
        <%= item.name %>
      </div>
      <div class="item-size left">
        <%= item.size %>
      </div>
      <div class="item-desc left">
        <%= item.description %>
      </div>
      <div class="item-price left">
        <%= item.price %>
      </div>
      <div class="item-price left">
        <%= f.text_field :quantity %>
      </div>
    </div>
  </li>
</ul>
<% end %>
<%= f.submit "Заказать" %>
<% end %>
</div>
<% end %>

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

B
Boris Penkovsky, 2014-11-29
@Able1991

To get started - use another link
rusrails.ru/active-record-associations
2.4. Communication has_many :through
And what kind of infernal migration in general? write like a human

create_table :carts_items do |t|
  t.references :card
  t.references :item
  t.decimal :quantity
end

Then read about fields_for and accepts_nested_attributes_for

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question