Gaelle
Gaelle

Reputation: 599

"merge" two arrays and iterate through the new array in Rails

Let's say I have

@colors = @product.colors.all
@storages = Storage.all

I need to loop through all combinations for these two and create an entry in a different model

How to tell the app to run this call for each color,storage and assign corresponding ids?

Stock.find_or_create_by_product_id(:product_id => @id, :color_id => XXX, :storage_id => XXX)

Upvotes: 2

Views: 600

Answers (1)

coreyward
coreyward

Reputation: 80041

I've got a secret for you: Ruby has documentation. There are lots of really awesome methods that are hidden from the bad developers that you can use to look awesome to your co-workers and they're all revealed to those in the know in the documentation. For example, Array#product is a really awesome method that will take another array as an argument and return an array with every combination of those two arrays (matter of fact, it'll take an unlimited number of arrays and return all combinations of all of the arrays). Pretty cool, right?

Here's how you might use it to make your situation easier:

@colors = @product.colors.all
@storages = Storage.all

@colors.product(@storages).each do |color, storage|
  Stock.find_or_create_by_product_id(:product_id => @id, :color_id => color.id, :storage_id => storage.id)
end

Welcome to the secret club. :)

Upvotes: 3

Related Questions