Configure default values for store attributes
masterYou can provide default values for store_attribute using the default option. This follows Rails attribute behavior:
- A default value is only populated if no value for the entire store attribute was set (i.e., only when creating a new record).
- Default values persist as soon as the record is saved.
Behavior for missing keys:
By default, store_attribute returns the default value even if the record is persisted but the specific attribute name is not present in the store hash. To change this so it returns nil instead, set store_attribute_unset_values_fallback_to_default = false.
class User < ActiveRecord::Base
# Returns default even if key is missing in DB
store_attribute :extra, :expired_at, :date, default: -> { 2.days.from_now }
end
# To return nil instead of default for missing keys:
class User < ApplicationRecord
self.store_attribute_unset_values_fallback_to_default = false
end
# Or globally in an initializer:
# StoreAttribute.store_attribute_unset_values_fallback_to_default = false