ActiveRecord insert_all の制約

投稿日: 2021年 3月 18日

insert_all を使うと、一括で複数のレコードのインサートが行える

Book.insert_all([
  { id: 1, title: "Rework", author: "David" },
  { id: 1, title: "Eloquent Ruby", author: "Russ" }
])

ただし、中間テーブルへの insert_all はできない

irb(main):010:0> pokemon.abilities.insert_all([{pokemon_no: 1, ability_id: 2}])
Traceback (most recent call last):
        7: from /home/gandhi/.rbenv/versions/3.0.0/bin/irb:23:in `<main>'
        6: from /home/gandhi/.rbenv/versions/3.0.0/bin/irb:23:in `load'
        5: from /home/gandhi/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/irb-1.3.0/exe/irb:11:in `<top (required)>'
        4: from (irb):9:in `<main>'
        3: from (irb):10:in `rescue in <main>'
        2: from /home/gandhi/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/activerecord-6.1.3/lib/active_record/associations/collection_proxy.rb:1109:in `insert_all'
        1: from (eval):3:in `insert_all'
ArgumentError (Bulk insert or upsert is currently not supported for has_many through association)

ArgumentError (Bulk insert or upsert is currently not supported for has_many through association)

とあり、できない様子(has_many through は中間テーブルを介した多対多の関係)

代わりに生のSQLを実行するほかなさそう

参考記事

https://blog.saeloun.com/2020/06/10/rails-support-bulk-insert-on-relation.html

プログラミングに関するオススメ書籍