views:

40

answers:

1

Hi I'm very new to rails and need some help on iterating through nested arrays. I'm trying to figure out how to do mass-inserts for each values that is different between the make, model and color of cars.

The params that are pass are:

"make" => ["Honda", "Honda"],
"model" => ["Civic", "Accord"],
"color" => [{"Black", "White", "Red"}, {"Black", "White"}]

So with these params passed, I wanted to have 5 inserts to occur.

1. Honda - Civic - Black
2. Honda - Civic - White
3. Honda - Civic - Red
4. Honda - Accord - Black
5. Honda - Accord - White

Here what I've got so far that pushes the insert query that builds it. But I'm unsure how to make it insert 5 times according to what I've listed above:

def self.cars(make, model, color)
  inserts = []
    color.each do |i|
      inserts.push "('#{make}', '#{model}', '#{i}')"
     end

  Foo.connection.execute "INSERT INTO car_inventory (make, model, color) VALUES #{inserts.join(", ")}"
end
A: 

Your insert method looks alright, but I've added sql sanitizing to the inputs. Standard rails inserts will sanitize for you, but when building your own queries, you'll want to sanitize input something like this to protect yourself from sql injections attacks.

def self.cars(make, model, colors)
  inserts = []
    colors.each do |color|
      inserts.push "('#{Foo.connection.quote(make)}', '#{Foo.connection.quote(model)}', '#{Foo.connection.quote(color)}')"
     end

  Foo.connection.execute "INSERT INTO car_inventory (make, model, color) VALUES #{inserts.join(", ")}"
end

Your controller should then look contain code something like this:

params["make"].each_with_index |make, index|
  Foo.cars(make, params["model"][index], params["color"][index])
end
Jeremy
Thanks Jeremy, I'll give that a try. Makes sense to use an index while iterating. Also, thx for the sanitizing suggestion.
Jeremy, would you be so kind as to help with similar issue. I figured out how still use form_for to and nested arrays to post to the controller. But I'm not sure how to do mass-inserts with it. I have the following params: "car"=>{"make"=>"Honda", "color"=>["0", "Black", "0", "White", "0", "Red"], "model"=>"Accord", "tinted"=>"yes"}. Is there anyway to have active model do 3 inserts at once seeing that there are 3 'colors' in the params?