简体   繁体   中英

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

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

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

Do you have a model for that table? Then you could just use plain ActiveRecord:

data = 1.upto(10000).map { |i| { name: "User #{i}" } }
User.create data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM