Aliased attributes with insert_all and upsert_all method

Dam Tien HungDam Tien Hung
2 min read

Rails 7.1 introduces the ability to use aliased attributes with insert_all and upsert_all methods. This feature allows you to use aliases when bulk inserting or updating records, which can be especially useful when dealing with complex database schemas or legacy database systems.

insert_all and upsert_all

Before Rails 6 we had update_all and delete_all.

Rails 6 added 3 methods insert_all, insert_all! and upsert_all to ActiveRecord::Persistence .

insert_all and insert_all! are methods in ActiveRecord::Persistence that allow bulk insertion of records into the database.
upsert_all is another method that can be used to insert or update multiple records in a single statement. upsert_all is only supported on databases that support the ON CONFLICT clause, like PostgreSQL.
All these methods bypass ActiveRecord validations and callbacks, so you need to be careful when using them to ensure the data remains consistent with your application's business rules.

alias_attribute

alias_attribute is a method in Ruby on Rails that allows you to create aliases for attributes in your ActiveRecord models.

In Rails 7.1, alias_attribute was enhanced to allow for the use of aliased attributes in insert_all and upsert_all methods.

class User < ApplicationRecord
  # database column is `name`. `full_name` is the alias.
  alias_attribute :full_name, :name
end

Before Rails 7.1

# rails console
> User.insert_all [{ full_name: "Johnny" }]
=> # unknown attribute 'full_name' for User. (ActiveModel::UnknownAttributeError)

After Rails 7.1

# rails console
> User.insert_all [{ full_name: "Johnny" }]
=> # User Insert

So this can be useful when:

  • Importing data from an external source that uses different attribute names.

  • Exposing an API that uses different attribute names from your internal models.

So in summary, Rails 7.1 introduces support for using aliased attributes in insert_all and upsert_all, giving you more flexibility when bulk inserting and updating data.

Please check out this pull request for more details.

1
Subscribe to my newsletter

Read articles from Dam Tien Hung directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dam Tien Hung
Dam Tien Hung