diff --git a/lib/active_record/typed_store/field.rb b/lib/active_record/typed_store/field.rb index b1bc772..34dbd54 100644 --- a/lib/active_record/typed_store/field.rb +++ b/lib/active_record/typed_store/field.rb @@ -11,12 +11,12 @@ def initialize(name, type, options={}) @accessor = options.fetch(:accessor, true) @name = name + @array = options.fetch(:array, false) if options.key?(:default) @default = extract_default(options[:default]) end @null = options.fetch(:null, true) @blank = options.fetch(:blank, true) - @array = options.fetch(:array, false) end def has_default? @@ -27,6 +27,8 @@ def cast(value) casted_value = type_cast(value) if !blank casted_value = default if casted_value.blank? + elsif array && has_default? + casted_value = default if value.nil? elsif !null casted_value = default if casted_value.nil? end diff --git a/spec/active_record/typed_store_spec.rb b/spec/active_record/typed_store_spec.rb index 794a040..4714941 100644 --- a/spec/active_record/typed_store_spec.rb +++ b/spec/active_record/typed_store_spec.rb @@ -524,7 +524,7 @@ describe 'model.typed_stores' do it "can access keys" do stores = model.class.typed_stores - expect(stores[:settings].keys).to eq [:no_default, :name, :email, :cell_phone, :public, :enabled, :age, :max_length, :rate, :price, :published_on, :remind_on, :published_at_time, :remind_at_time, :published_at, :remind_at, :total_price, :shipping_cost, :grades, :tags, :nickname, :author, :source, :signup, :country] + expect(stores[:settings].keys).to eq [:no_default, :name, :email, :cell_phone, :public, :enabled, :age, :max_length, :rate, :price, :published_on, :remind_on, :published_at_time, :remind_at_time, :published_at, :remind_at, :total_price, :shipping_cost, :grades, :tags, :subjects, :nickname, :author, :source, :signup, :country] end it "can access keys even when accessors are not defined" do @@ -889,9 +889,15 @@ expect(model.reload.grades).to be == [[1, 2], [3, 4, 5]] end + it 'defaults to [] if provided default is not an array' do + model.update(subjects: nil) + expect(model.reload.subjects).to be == [] + end + + # Not sure about pg_native and if this test should be outside of this block. it 'retreive default if assigned null' do model.update(tags: nil) - expect(model.reload.tags).to be == [] + expect(model.reload.tags).to be == ['article'] end end end diff --git a/spec/support/models.rb b/spec/support/models.rb index abe04b0..45779e9 100644 --- a/spec/support/models.rb +++ b/spec/support/models.rb @@ -43,7 +43,8 @@ def define_columns(t, array: false) if t.is_a?(ActiveRecord::TypedStore::DSL) t.integer :grades, array: true - t.string :tags, array: true, null: false, default: [].to_yaml + t.string :tags, array: true, null: false, default: ['article'] + t.string :subjects, array: true, null: false, default: ['mathematics'].to_yaml t.string :nickname, blank: false, default: 'Please enter your nickname' end