byroot / activerecord-typedstore

ActiveRecord::Store but with type definition
MIT License
439 stars 57 forks source link

Store defaults to database #37

Open bemueller opened 8 years ago

bemueller commented 8 years ago

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.

byroot commented 8 years ago

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.

jcw- commented 5 years ago

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