From fecd8becbe157912cbb4f160a5ef63dae3143374 Mon Sep 17 00:00:00 2001 From: Jonathan Hefner Date: Tue, 18 Oct 2022 15:42:01 -0500 Subject: [PATCH] Add read_attribute_for_database The `BeforeTypeCast` module defines `read_attribute_before_type_cast`, `attributes_before_type_cast`, and `*_before_type_cast` attribute methods. It also defines `attributes_for_database` and `*_for_database` attribute methods, but no corresponding `read_attribute_for_database` method. This commit adds the missing `read_attribute_for_database` method. --- .../attribute_methods/before_type_cast.rb | 17 +++++++++++++++++ .../test/cases/attribute_methods_test.rb | 14 ++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb index b34c0f32492af..e4d562ad62276 100644 --- a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb +++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb @@ -52,6 +52,23 @@ def read_attribute_before_type_cast(attr_name) attribute_before_type_cast(name) end + # Returns the value of the attribute identified by +attr_name+ after + # serialization. + # + # class Book < ActiveRecord::Base + # enum status: { draft: 1, published: 2 } + # end + # + # book = Book.new(status: "published") + # book.read_attribute(:status) # => "published" + # book.read_attribute_for_database(:status) # => 2 + def read_attribute_for_database(attr_name) + name = attr_name.to_s + name = self.class.attribute_aliases[name] || name + + attribute_for_database(name) + end + # Returns a hash of attributes before typecasting and deserialization. # # class Task < ActiveRecord::Base diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 2663a7344a6bf..90dc39de6337c 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -215,7 +215,17 @@ def setup end end - test "read attributes_for_database" do + test "read_attribute_for_database" do + topic = Topic.new(content: ["ok"]) + assert_equal "---\n- ok\n", topic.read_attribute_for_database("content") + end + + test "read_attribute_for_database with aliased attribute" do + topic = Topic.new(title: "Hello") + assert_equal "Hello", topic.read_attribute_for_database(:heading) + end + + test "attributes_for_database" do topic = Topic.new topic.content = { "one" => 1, "two" => 2 } @@ -226,7 +236,7 @@ def setup assert_not_equal topic.attributes, before_type_cast_attributes end - test "read attributes_after_type_cast on a date" do + test "read attributes after type cast on a date" do tz = "Pacific Time (US & Canada)" in_time_zone tz do