ActiveRecord ::使用默认值存储

And*_*rew 11 activerecord store ruby-on-rails

使用新的ActiveRecord :: Store进行序列化,文档提供了以下示例实现:

class User < ActiveRecord::Base
  store :settings, accessors: [ :color, :homepage ]
end
Run Code Online (Sandbox Code Playgroud)

是否可以使用默认值声明属性,类似于:

store :settings, accessors: { color: 'blue', homepage: 'rubyonrails.org' }
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 19

不,没有办法在store通话中提供默认值.该store很简单:

def store(store_attribute, options = {})
  serialize store_attribute, Hash
  store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
end
Run Code Online (Sandbox Code Playgroud)

并且所有store_accessor操作都是遍历:accessors并为每个方法创建accessor和mutator方法.如果您尝试使用Hash,:accessors最终会向您添加一些store您不想要的东西.

如果要提供默认值,则可以使用after_initialize钩子:

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
Run Code Online (Sandbox Code Playgroud)

  • +1,@mu 通常在这种情况下我使用`set if not set` 习语,即`self.color ||='blue'; self.homepage ||= 'rubyonrails.org'`。这避免了“脏”检查.. (2认同)