Rails 7.1 allows using aliased attributes with insert_all and upsert_all

railsDecember 06, 2023Dotby Alkesh Ghorpade

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.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at [email protected] or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right