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:
commit
48ecee1c44
2 changed files with 29 additions and 2 deletions
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue