K
K
kstepanovdev2016-10-03 12:27:48
Ruby on Rails
kstepanovdev, 2016-10-03 12:27:48

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

It turns out such a form that sends only the data of the last product in the array, and not all.
<%= 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 %>

Here is such a canoe. If there are thoughts and / or pissing rags, then I'm ready :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Givandos, 2016-10-04
@kstepanovdev

<%= f.fields_for :products do |products_form| %>
<% @products.each do |product| %>

In fact, the "fields_for" helper is already an iteration method, so "each" is superfluous here.
Hence the line
will become simpler:
In general, I would recommend something like this:
<%= 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 %>

Only in the order model do not forget to get the attributes of the child model - accepts_nested_attributes_for :order_items
As a result, in the request (by the way, the request itself must point to the controller that will store the order model) you should not just have {"products"=>{"quantity" =>"6", "product_id"=>"2"}}, but something like
{"order_items_attributes"=>[{"quantity"=>"6", "product_id"=>"2"}, { "quantity"=>"3", "product_id"=>"5"}]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question