Using the new ActiveRecord::Store for serialization, the docs give the following example implementation:
class User < ActiveRecord::Base
store :settings, accessors: [ :color, :homepage ]
end
Is it possible to declare attributes with default values, something akin to:
store :settings, accessors: { color: 'blue', homepage: 'rubyonrails.org' }
?
in Ruby, :: accesses static class or module constants. ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
The reason is that store_accessor is basically just a shortcut which defines getter and setter methods: # here is a part of store_accessor method code, you can take a look at # full implementation at # http://apidock.com/rails/ActiveRecord/Store/ClassMethods/store_accessor _store_accessors_module.module_eval do keys. ...
No, there's no way to supply defaults inside the store
call. The store
macro is quite simple:
def store(store_attribute, options = {})
serialize store_attribute, Hash
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
end
And all store_accessor
does is iterate through the :accessors
and create accessor and mutator methods for each one. If you try to use a Hash with :accessors
you'll end up adding some things to your store
that you didn't mean to.
If you want to supply defaults then you could use an after_initialize
hook:
class User < ActiveRecord::Base
store :settings, accessors: [ :color, :homepage ]
after_initialize :initialize_defaults, :if => :new_record?
private
def initialize_defaults
self.color = 'blue' unless(color_changed?)
self.homepage = 'rubyonrails.org' unless(homepage_changed?)
end
end
I wanted to solve this too and ended up contributing to Storext:
class Book < ActiveRecord::Base
include Storext.model
# You can define attributes on the :data hstore column like this:
store_attributes :data do
author String
title String, default: "Great Voyage"
available Boolean, default: true
copies Integer, default: 0
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With