不,没有办法在store
调用中提供默认值。该store
macro很简单:
def store(store_attribute, options = {})
serialize store_attribute, Hash
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
end
而且所有store_accessor
所做的是通过迭代:accessors
并为每一个访问和mutator方法。如果你试图用:accessors
来使用Hash,那么你最终会在你的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
+1,@mu通常在这种情况下,我使用'set if not set'成语,即'self.color || ='blue'; self.homepage || ='rubyonrails.org'。这样可以避免'脏'检查。 – 2012-03-12 05:52:01
@KandadaBoggu:'|| ='唯一的缺点是如果你有布尔属性,使用肮脏使他们都一致。可惜没有像Perl的'// ='那样的“set if not defined”。 – 2012-03-12 06:02:09
是的,这是真的,如果他们使用'|| ='成语,就必须以不同的方式对待布尔。 – 2012-03-12 07:01:46