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.
class User < ApplicationRecord
# database column is `name`. `full_name` is the alias.
alias_attribute :full_name, :name
end
# rails console
> User.insert_all [{ full_name: "John Doe" }]
=> # unknown attribute 'full_name' for User. (ActiveModel::UnknownAttributeError)
# rails console
> User.insert_all [{ full_name: "Jane Doe" }]
=> # User Insert
> User.last
=> #<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.
If this blog was helpful, check out our full blog archive.