0

こんにちは、1 つのクエリで複数のレコードを作成したい Rails アプリがあります。

これは私のコードです

   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}"

私が得ているエラーは、mysql構文のエラーです

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

("ユーザー名")、("ユーザー名") のようにしたいのはわかっていますが、達成できません。この値の形式を達成する方法を教えてください。

4

2 に答える 2

2

そのテーブルのモデルはありますか?次に、プレーンな ActiveRecord を使用できます。

data = 1.upto(10000).map { |i| { name: "User #{i}" } }
User.create data
于 2016-08-26T13:36:50.853 に答える
2

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(",")

于 2016-08-26T13:10:35.277 に答える