Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::Store with default values

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' }

?

like image 893
Andrew Avatar asked Mar 12 '12 03:03

Andrew


People also ask

What is ActiveRecord :: Base in Ruby?

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.

What is Store_accessor?

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. ...


2 Answers

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
like image 152
mu is too short Avatar answered Sep 19 '22 17:09

mu is too short


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
like image 29
Ramon Tayag Avatar answered Sep 21 '22 17:09

Ramon Tayag