DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Default values for attributes when retrieving the store model

raivil opened this issue · comments

Hey,
I'm trying to configure default values for attributes but I'm not sure if I'm doing something wrong or it's something not supported/bug.

Defining "default" will return the default value only when instantiating the store model, but not when retrieving an attribute

here's a simplified example that shows the behavior.

class Settings < ApplicationRecord
   attribute :colors, Colors.to_type
   validates :colors, store_model: true, allow_blank: true 
end

class Settings::Colors
  include StoreModel::Model

  attribute :bg_default, :string, default: "#ff0000"
  attribute :bg_overlay, :string, default: "#a6af1d"
end

irb(main):040:0> Settings.last.colors                                                                        
=> #<Settings::Colors bg_default: nil, bg_overlay: nil,

irb(main):041:0> Settings.new.colors
=> #<Settings::Colors bg_default: #ff0000, bg_overlay: #a6af1d,

irb(main):042:0> Settings.new.colors.bg_default
=> "#ff0000"
irb(main):043:0> Settings.last.colors.bg_default
=> nil 

Hi @raivil! This is how attributes API works, you have to add the default to the database to make it work