Answer the question
In order to leave comments, you need to log in
How to implement a home page for adding items to cart using nested attributes?
Need advice, if you can help - help out, otherwise it's a beard.
Can't add to cart with a single button. Rails 5. The bottom line is - usually for each product a form is generated with a button and, for example, a window for specifying the number of products.
I need to make, in fact, the only form for all this goodness, so that by clicking "Add to Cart" those goods where the specified quantity in the boxes is not zero fall into the basket.
As I understand it, you need to use nested_attributes to pass an array of parameters, but so far all that I have done is nothing. Maybe someone can help with advice.
There are three models, in fact.
Cart
has_many :cart_items
Products
has_many :cart_items
#тут, я так понимаю, нужно это
accepts_nested_attributes_for :cart_items
CartItems
belongs_to :cart
belongs_to :product
<%= form_for @order_item, remote: true do |f| %>
<%= f.fields_for :products do |products_form| %>
<% @products.each do |product| %>
<%= product.name %>
Unit Price:<%= number_to_currency product.price %>
<%= f.number_field :quantity, value: 1, class: "form-control", min: 1 %>
<%= f.hidden_field :product_id, value: product.id %>
<% end %>
<% end %>
<%= f.submit "Add to Cart", class: "btn btn-primary" %>
<% end %>
Answer the question
In order to leave comments, you need to log in
<%= f.fields_for :products do |products_form| %>
<% @products.each do |product| %>
<%= form_for @order, remote: true do |f| %>
<%= f.fields_for :order_items, @products do |product|
<%= product.hidden_field :product_id %>
<%= product.number_field :quantity, value: 1 %>
<% end %>
<% end %>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question