Search code examples
mysqlsqlruby-on-railsruby-on-rails-4.2batch-insert

Ruby on Rails update multiple records in a single query


hi i have a rails app in which i want to create multiple records in the single query

this is my code

   inserts = []

    1000.times do
      inserts.push "user name"
    end

    inserts = inserts.map {|bar| "(#{bar.to_s})"}.join(",")

    ActiveRecord::Base.connection.execute "INSERT INTO `user_dat`.`user_inserts` (`name`) VALUES #{inserts}"

What error i am getting is the error in the mysql syntax

INSERT INTO `batch_insert`.`batch_inserts` (`name`) VALUES (user name),(user name),(user name),(user name),(user name),(user name),(user name).... upto 1000

i know i want it like ("user name"), ("user name") but i am not able to achieve it can someone please tell me how can i achieve this format of values


Solution

  • If the problem is only to put quotes around usernames, the answer is to replace string inserts = inserts.map {|bar| "(#{bar.to_s})"}.join(",")

    with inserts = inserts.map {|bar| %Q[("#{bar.to_s}")]}.join(",")