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 59aa3a8b53..33ca3d38b6 100644 --- a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb +++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb @@ -29,7 +29,7 @@ module ActiveRecord extend ActiveSupport::Concern included do - attribute_method_suffix "_before_type_cast" + attribute_method_suffix "_before_type_cast", "_for_database" attribute_method_suffix "_came_from_user?" end @@ -72,6 +72,10 @@ module ActiveRecord @attributes[attr_name].value_before_type_cast end + def attribute_for_database(attr_name) + @attributes[attr_name].value_for_database + end + def attribute_came_from_user?(attr_name) @attributes[attr_name].came_from_user? end diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index e10f70a0b6..2eb8e76ade 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -54,7 +54,7 @@ module ActiveRecord end module ClassMethods - ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast id_was id_in_database).to_set + ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast id_was id_in_database id_for_database).to_set def instance_method_already_implemented?(method_name) super || primary_key && ID_ATTRIBUTE_METHODS.include?(method_name) diff --git a/activerecord/test/cases/enum_test.rb b/activerecord/test/cases/enum_test.rb index 1a6e1a2698..e4cb3ae26a 100644 --- a/activerecord/test/cases/enum_test.rb +++ b/activerecord/test/cases/enum_test.rb @@ -290,7 +290,7 @@ class EnumTest < ActiveRecord::TestCase assert_predicate Book.illustrator_visibility_invisible.create, :illustrator_visibility_invisible? end - test "_before_type_cast" do + test "attribute_before_type_cast" do assert_equal 2, @book.status_before_type_cast assert_equal "published", @book.status @@ -300,6 +300,16 @@ class EnumTest < ActiveRecord::TestCase assert_equal "published", @book.status end + test "attribute_for_database" do + assert_equal 2, @book.status_for_database + assert_equal "published", @book.status + + @book.status = "published" + + assert_equal 2, @book.status_for_database + assert_equal "published", @book.status + end + test "invalid definition values raise an ArgumentError" do e = assert_raises(ArgumentError) do Class.new(ActiveRecord::Base) do