Faster CSV contact imports

Ruby · Rails · intermediate · modification

Speeds up contact imports by replacing the per-row `create!` with bulk inserts. `ContactImport#call` now collects the rows first, skipping those without an email, and writes them with `Contact.insert_all` in batches of 1,000 inside one transaction. Duplicates are left to the existing unique index on `(account_id, email)`: `insert_all` skips a conflicting row, and its `RETURNING id` result gives the number of rows actually written, so `skipped` still counts blank and duplicate rows together. `contact_import_test.rb` keeps the existing tests and adds tests for a repeated row in one file, an address that belongs to another account, and a file larger than one batch.

Ruby 4.0, Rails 8.1 (SQLite in development and test, PostgreSQL 16 in production; nothing here depends on the database). `csv` is a bundled gem since Ruby 3.4 and is already in the app's Gemfile. `Contact` (existing, unchanged): `belongs_to :account`; `before_validation :normalize_email`, which sets `self.email = Contact.normalize_email_address(email)`; `Contact.normalize_email_address(email)` returns `email.to_s.strip.downcase`; `validates :email, presence: true, uniqueness: { scope: :account_id }`. The `contacts` table has `account_id` (not null, foreign key), `name` (nullable), `email` (string, not null) and the timestamps, with a unique index on `(account_id, email)`. The mail integration's lookup (existing, unchanged) is `Current.account.contacts.find_by!(email: Contact.normalize_email_address(params.expect(:email)))`, and `ActiveRecord::RecordNotFound` answers 404. `ContactImportsController#create` (existing, unchanged) is reachable only by the account's admins, rejects a file over 5 MB, a header other than `name,email` or malformed CSV with 422, and calls `ContactImport.new(account: Current.account, csv: file.read).call`. Uploaded files are UTF-8. Per the Rails API docs (`ActiveRecord::Relation#insert_all`), `insert_all` "does not instantiate any models nor does it trigger Active Record callbacks or validations"; by default it still sets `created_at`/`updated_at`. Tests are Minitest model tests with inline records.

Requirements

Files touched

Review this PR

Ruby practice