Rails 7.1 allows using aliased attributes with insert_all/upsert_all

Aditya Bhutani

By Aditya Bhutani

on January 11, 2023

This blog is part of our  Rails 7 series.

Before Rails 6 we had update_all and delete_all. Rails 6 added insert_all and upsert_all.

insert_all : This method can insert multiple records with a single SQL INSERT statement.

upsert_all : This method updates the records if they exist or inserts them into the database with a single SQL INSERT statement.

alias_attribute : Allows you to make aliases for attributes, which include a getter, a setter, and a predicate.

Rails 7.1 allows using aliased attributes with insert_all and upsert_all. Previously whenever we added an alias for an attribute, we couldn't use it for insert_all and upsert_all.

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

Before Rails 7.1

1# rails console
2> User.insert_all [{ full_name: "John Doe" }]
3=> # unknown attribute 'full_name' for User. (ActiveModel::UnknownAttributeError)

After Rails 7.1

1# rails console
2> User.insert_all [{ full_name: "Jane Doe" }]
3=> # User Insert
4
5> User.last
6=> #<User id: 6, name: "Jane Doe", created_at: Mon, 21 Nov 2022 18:07:11.349000000 UTC +00:00, updated_at: Mon, 21 Nov 2022 18:07:11.349000000 UTC +00:00>

Now we can use alias attribute with insert_all and upsert_all.

Please check out this pull request for more details.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.