diff options
author | Kir Shatrov <shatrov@me.com> | 2017-06-21 13:58:07 -0400 |
---|---|---|
committer | Kir Shatrov <shatrov@me.com> | 2017-08-04 16:47:55 +0300 |
commit | a0751d27c52185b86370baf6a565e757092646de (patch) | |
tree | fa6a305d42e5b736fd3534e59ee1c7c25cbcfe5c /activerecord/lib/active_record | |
parent | 904f1a8747958129124d86b44e36c5f0263e0125 (diff) | |
download | rails-a0751d27c52185b86370baf6a565e757092646de.tar.gz rails-a0751d27c52185b86370baf6a565e757092646de.tar.bz2 rails-a0751d27c52185b86370baf6a565e757092646de.zip |
Do not let use `serialize` on native JSON/array column
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/attribute_methods/serialization.rb | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 6ed45d8737..acd47629dd 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -5,6 +5,16 @@ module ActiveRecord module Serialization extend ActiveSupport::Concern + class ColumnNotSerializableError < StandardError + def initialize(name, type) + super <<-EOS.strip_heredoc + Column `#{name}` of type #{type.class} does not support `serialize` feature. + Usually it means that you are trying to use `serialize` + on a column that already implements serialization natively. + EOS + end + end + module ClassMethods # If you have an attribute that needs to be saved to the database as an # object, and retrieved as the same object, then specify the name of that @@ -60,9 +70,23 @@ module ActiveRecord end decorate_attribute_type(attr_name, :serialize) do |type| + if type_incompatible_with_serialize?(type) + raise ColumnNotSerializableError.new(attr_name, type) + end + Type::Serialized.new(type, coder) end end + + private + + def type_incompatible_with_serialize?(type) + type.is_a?(ActiveRecord::Type::Json) || + ( + defined?(ActiveRecord::ConnectionAdapters::PostgreSQL) && + type.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array) + ) + end end end end |