开发者

Rails - Iterating through nested arrays

开发者 https://www.devze.com 2023-01-19 09:02 出处:网络
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

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" => ["Civi开发者_StackOverflow社区c", "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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消