diff --git a/lib/store_attribute/active_record/store.rb b/lib/store_attribute/active_record/store.rb index da43435..2cf7842 100644 --- a/lib/store_attribute/active_record/store.rb +++ b/lib/store_attribute/active_record/store.rb @@ -127,12 +127,11 @@ def store_attribute(store_name, name, type = :value, prefix: nil, suffix: nil, * _define_store_attribute(store_name) if !_local_typed_stored_attributes? || _local_typed_stored_attributes[store_name][:types].empty? || - # Defaults owner has changed, we must decorate the attribute to correctly propagate the defaults - ( - options.key?(:default) && _local_typed_stored_attributes[store_name][:owner] != self - ) + # Owner has changed (e.g., subclass adding to inherited store), + # we must re-decorate the attribute to correctly set up type casting and defaults + _local_typed_stored_attributes[store_name][:owner] != self - _local_typed_stored_attributes[store_name][:owner] = self if options.key?(:default) || !_local_typed_stored_attributes? + _local_typed_stored_attributes[store_name][:owner] = self if !_local_typed_stored_attributes? || _local_typed_stored_attributes[store_name][:owner] != self _local_typed_stored_attributes[store_name][:types][name] = [type, options] # In case #decorate_attribute has already been invoked, add new type information right away diff --git a/spec/cases/store_attribute_spec.rb b/spec/cases/store_attribute_spec.rb index 7291d1e..ed61955 100644 --- a/spec/cases/store_attribute_spec.rb +++ b/spec/cases/store_attribute_spec.rb @@ -102,6 +102,32 @@ expect(jamie).to be_active expect(jamie.salary).to eq 100 end + + it "typecasts inherited typed store attributes without defaults on reload" do + subclass = Class.new(User) do + store_attribute :jparams, :amount, :decimal, precision: 15, scale: 2 + end + + record = subclass.create!(jparams: {"amount" => "12345.67"}) + record.reload + + expect(record.amount).to eq BigDecimal("12345.67") + expect(record.jparams["amount"]).to eq BigDecimal("12345.67") + end + + it "typecasts typed store attributes without defaults on reload" do + klass = Class.new(ActiveRecord::Base) do + self.table_name = "users" + + store_attribute :jparams, :amount, :decimal, precision: 15, scale: 2 + end + + record = klass.create!(jparams: {"amount" => "12345.67"}) + record.reload + + expect(record.amount).to eq BigDecimal("12345.67") + expect(record.jparams["amount"]).to eq BigDecimal("12345.67") + end end context "custom types" do