Make a list without EACH in Rails

Asked

Viewed 125 times

0

I would like to know how to create a product listing. Where I have a part of the system that creates a customer and then I can place an order for that customer. By selecting the customer I can add items to that customer order. Perfect after selecting all this. There will be a part where I need to list all the items that are CHOSEN in the items. I need PRODUCT NAME AND QUANTITY THAT WAS SELECTED.

Example: Products QTD

Rice 15 beans 30

That’s my goal, but it’s not happening like this, because if I have another customer who makes the order for RICE the product name repeats with QTD. Example below: Products QTD

Rice 15 beans 30 Rice 15 Rice 15

Code from my view:

 <div class="box-body no-padding">
<table class="table table-condensed">
  <tr>
    <th>Produto</th>
    <th>Quantidade total</th>

  </tr>
  <% @items.each do |item| %>
    <tr>
      <td><%= item.product.name %></td>
      <td><%= item.product.items.sum(:qtd_product) %></td>
    </tr>
  <% end %>            
</table>

1 answer

1


It happens because of how you did the create of your Product. If you want a list only with the products of a certain customer you must modify in the controller @products = Product.where(user: {Seu User Desejado})

If a customer creates an order with Rice and another one with Rice and you do not want them to separate, use this logic on products#create:

def create
  @product = Product.new(product_params)
  produto_ja_existente = Product.find_by(name: @product.name) 
  if produto_ja_existente
    produto_ja_existente.items.qtd_product += @product.items.qtd_product
    produto_ja_existente.save
  else
   @product.save
  end
  redirect_to products_path
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.