问题描述
使用新的ActiveRecord ::商店系列化,的文档给出如下示例实现:
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' }
推荐答案
没有,有没有办法来提供存储
调用中的默认值。该<$c$c>store$c$c>宏是相当简单:
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
和所有的 store_accessor
并通过迭代:访问
和创建存取和突变的方法为每一个。如果您尝试使用哈希与:访问
你最终会加入一些东西到你的存储
你没T意思。
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.
如果你要提供的默认值,那么你可以使用 after_initialize
挂钩:
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
这篇关于ActiveRecord的::商店使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!