1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #46283 from jonathanhefner/active_record-read_attribute_for_database

Add `read_attribute_for_database`
This commit is contained in:
Jonathan Hefner 2022-10-19 23:42:59 -05:00 committed by GitHub
commit 48ecee1c44
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 2 deletions

View file

@ -52,6 +52,23 @@ module ActiveRecord
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

View file

@ -215,7 +215,17 @@ class AttributeMethodsTest < ActiveRecord::TestCase
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 @@ class AttributeMethodsTest < ActiveRecord::TestCase
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