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)
归档时间: |
|
查看次数: |
4853 次 |
最近记录: |