ruby-on-railspostgresqlperformanceactivemodel

Rails create single record VS create multiple records PERFOMANCE difference


Is there speed difference between this methods? (POSTGRESQL)

First

products = [{...},{...},...]
products.each { |p|
  Product.create(p)
}

Second

products = [{...},{...},...]
Product.create(products)

Both methods for each record make two queries:

1) INSERT INTO "products" VALUES (..)
2) UPDATE "products" SET "updated_at"...

Solution

  • max is right: both queries are the same, and you can write custom SQL. This is only a local solution though.

    But I've found activerecord-import gem that is doing the same – bulk objects import.

    products = [{...},{...},...]
    Product.import(products)