Add support for :default option
Closed this issue · 6 comments
skydan commented
Does it make sense to add support for :default
option on top of set of typecasting options?
palkan commented
I think, it makes sense.
Though it's not clear how exactly we want it to work. For example:
class Product < ActiveRecord::Base
store_attribute :settings, :color, :string, default: "red"
end
How this should work?
- accessor returns the default value (seems reasonable)
Product.new.color #=> "red"
- should store attribute contain the default?
Product.new.settings #=> ? should this be `{ "color" => "red"}` or `{}`?
- should we persist the default value on save?
Product.new.save!
#=> INSERT INTO products (settings) values ('{"color":"red"}'); ???
skydan commented
How this should work?
- accessor returns the default value (seems reasonable)
Product.new.color #=> "red"
- should store attribute contain the default?
Product.new.settings #=> ? should this be `{ "color" => "red"}` or `{}`?
- should we persist the default value on save?
Product.new.save! #=> INSERT INTO products (settings) values ('{"color":"red"}'); ???
I think that behavior should be the same as when we pass this attribute explicitly:
Product.new.settings #=>`{ "color" => "red"}`
Product.new(color: "red").settings #=>`{ "color" => "red"}`
Product.new.save!
#=> INSERT INTO products (settings) values ('{"color":"red"}');
Product.new(color: "red").save!
#=> INSERT INTO products (settings) values ('{"color":"red"}');
palkan commented
I think, we need a parity with Attributes API here:
# create_table :posts do |t|
# t.string :data
# end
class Post < ActiveRecord::Base
attribute :data, :datetime, default: -> { Time.current }
end
How does this behave? Not sure, need to check.
theycallmeswift commented
+1 that this would be valuable and should mirror the attributes API.
SumLare commented
I'm gonna take a look at it this week if nobody minds.