Answer the question
In order to leave comments, you need to log in
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
class Item < ActiveRecord::Base
belongs_to :category
has_and_belongs_to_many :carts
end
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
<%= 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
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 %>
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question