activerecord-typedstore icon indicating copy to clipboard operation
activerecord-typedstore copied to clipboard

Store defaults to database

Open bemueller opened this issue 9 years ago • 2 comments

Hi.

Due to the implementation of ActiveRecord::Type::Serialized#type_cast_for_database (Rails 4.2.5.x), in some cases default values aren't stored to the database.

class Data < ActiveRecord::Base
  typed_store :store do |t|
    t.boolean :bool, default: false
    t.string :hello
end

a = Data.create!(bool: true)
# representation of {bool: true} is stored in store column

b = Data.create!
# NULL  is stored in store column

c = Data.create!(hello: 'world')
# representation of {bool: false, hello: 'world'} is stored in store column

This results in an inconsistent view on the database and makes it hard to select all Datas where bool is false.

bemueller avatar Feb 15 '16 12:02 bemueller

This was done on purpose with serialized fields in mind (YAML / JSON in TEXT columns), but I see how it doesn't make sense for HStore / native JSON.

It should at least be configurable.

byroot avatar Feb 17 '16 18:02 byroot

Workaround - add a presence validation to your model for at least one of the fields with a default value, e.g. validates :bool, presence: true, this way the create! call will fail

jcw- avatar Feb 09 '19 07:02 jcw-