0

I'm populating an array with multiple elements (some of then are equals, thats what I want). My code is something like this:

def create
@order = Order.create()
@order.table = Table.find_by(:number => params['table'][0])
@products ||= []
@qtd = []
Product.all.each do |product|
  params['order'].each_pair do |ordered|
    if(product.id.to_s == ordered.first)
      for i in 0..ordered.second[0].to_i
        @order.products << product
        @order.save
      end
    end
  end
end

 binding.pry #here the @order.products is the way I want to

if @order.save
  flash[:success] = "Pedido criado com sucesso."
  redirect_to tables_path
else
  flash[:danger] = "Erro ao criar pedido."
  render :new
end
end

But When I go to rails console and do Order.last.products he dosen't show me de duplicated elements like I saved on my controller. Whats happening?

Eduardo Pedroso
  • 839
  • 3
  • 12
  • 30

1 Answers1

1

Well in your case you should be sending order information from client to server like

"order"=>{"line_items_attributes"=>{"0"=>{"quantity"=>"4", "id"=>"127"}}}

Instead of repeating the product id in the list, your should implement a concept of line items in your system. Line Items are the objects representing items that are added to your shopping cart and instead of repeating the product_id you can use term quantity.

Now you can have separate model called LineItem. Order can have many LineItems. LineItem has many products.

For more info see What is a "order line"?


For current Implementation:

<< method does not allow duplicate entries. It filters out the duplicates. Its basically relates products with order since order can have multiple products via some_table. It cannot relate same product to the order twice.

My suggestion would be, create a string field(column) called products and add the serialized array of product ids.

order.products = [1, 1, 3, 4,4,4].to_s

while accessing you de-serialize.

Community
  • 1
  • 1
Shiva
  • 11,485
  • 2
  • 67
  • 84