Rails 7.1 allows using aliased attributes with insert_all and upsert_all
Rails 7.1 introduces a significant enhancement to its data manipulation
capabilities by enabling the use of aliased attributes within the insert_all
and
upsert_all
methods.
This new feature streamlines the process of working with aliased attributes,
eliminating the need for manual attribute mapping
and
simplifying the overall data insertion
and
update workflows.
Before Rails 7.1
Before Rails 7.1,
utilizing aliased attributes with insert_all
and
upsert_all
.
Trying to pass an alias attribute to the insert_all
or
upsert_all
methods,
it would raise ActiveModel::UnknownAttributeError
.
class Book < ApplicationRecord
alias_attribute :title, :name
end
Book.insert_all [{ title: "Atomic Habits" }, { title: "Monk who..." }]
=> # unknown attribute 'title' for Book. (ActiveModel::UnknownAttributeError)
In Rails 7.1
Rails 7.1 allows the use of aliased attributes with insert_all and upsert_all.
You won't face any error when passing the alias attributes to the
insert_all
or
upsert_all
method.
class Book < ApplicationRecord
alias_attribute :title, :name
end
Book.insert_all [{ title: "Atomic Habits" }, { title: "Monk who..." }]
# Output of the above query
The ability to use aliased attributes with insert_all
and
upsert_all
offers several advantages:
Improved Readability: Aliased attributes enhance code readability by making attribute names more descriptive and self-explanatory.
Reduced Code Complexity: Automatic aliased attribute handling simplifies code structure and reduces potential errors.
Enhanced Maintainability: Simpler code and fewer manual mappings improve code maintainability and reduce debugging time.
Overall,
the introduction of aliased attribute support in insert_all
and
upsert_all
represents a valuable addition to Rails 7.1,
streamlining data manipulation tasks
and
promoting code clarity
and
maintainability.
To know more about this feature, please refer to this PR.