活动记录存储
Store
为您提供一个序列化周围的精简包装,用于将哈希存储在单个列中。这就像一个简单的键/值存储,当您不在乎在单个记录的上下文中查询该存储时,它会烘焙到您的记录中。
然后,您可以声明对该存储的访问器,然后可以像访问模型的任何其他属性一样访问它。这对于轻松地将存储键公开到表单或其他已经围绕仅访问模型上的属性而构建的位置非常有帮助。
每个访问器都带有脏跟踪方法(key_changed?
、key_was
和 key_change
)以及用于访问上次保存期间所做更改的方法(saved_change_to_key?
、saved_change_to_key
和 key_before_last_save
)。
注意:访问器没有 key_will_change!
方法,请改用 store_will_change!
。
确保将用于序列化存储的数据库列声明为文本,以便有足够的空间。
您可以设置自定义编码器,以将您的序列化属性编码/解码为不同格式。JSON、YAML、Marshal 开箱即用。通常它可以是提供 load
和 dump
的任何包装器。
注意:如果您正在使用结构化数据库数据类型(例如 PostgreSQL hstore
/json
或 MySQL 5.7+ json
),则不需要 .store 提供的序列化。只需改用 .store_accessor 来生成访问器方法。请注意,这些列使用字符串键控哈希,不允许使用符号进行访问。
注意:默认验证(uniqueness
除外)将起作用。例如,如果您想使用 hstore
检查 uniqueness
,您将需要使用自定义验证来处理它。
示例
class User < ActiveRecord::Base
store :settings, accessors: [ :color, :homepage ], coder: JSON
store :parent, accessors: [ :name ], coder: JSON, prefix: true
store :spouse, accessors: [ :name ], coder: JSON, prefix: :partner
store :settings, accessors: [ :two_factor_auth ], suffix: true
store :settings, accessors: [ :login_retry ], suffix: :config
end
u = User.new(color: 'black', homepage: '37signals.com', parent_name: 'Mary', partner_name: 'Lily')
u.color # Accessor stored attribute
u.parent_name # Accessor stored attribute with prefix
u.partner_name # Accessor stored attribute with custom prefix
u.two_factor_auth_settings # Accessor stored attribute with suffix
u.login_retry_config # Accessor stored attribute with custom suffix
u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
# There is no difference between strings and symbols for accessing custom attributes
u.settings[:country] # => 'Denmark'
u.settings['country'] # => 'Denmark'
# Dirty tracking
u.color = 'green'
u.color_changed? # => true
u.color_was # => 'black'
u.color_change # => ['black', 'green']
# Add additional accessors to an existing store through store_accessor
class SuperUser < User
store_accessor :settings, :privileges, :servants
store_accessor :parent, :birthday, prefix: true
store_accessor :settings, :secret_question, suffix: :config
end
可以使用 .stored_attributes 检索存储的属性名称。
User.stored_attributes[:settings] # => [:color, :homepage, :two_factor_auth, :login_retry]
覆盖默认访问器
所有存储的值都可通过 Active Record 对象上的访问器自动获取,但有时您希望专门化此行为。可以通过覆盖默认访问器(使用与属性相同的名称)并调用 super
来实际更改内容来实现此目的。
class Song < ActiveRecord::Base
# Uses a stored integer to hold the volume adjustment of the song
store :settings, accessors: [:volume_adjustment]
def volume_adjustment=(decibels)
super(decibels.to_i)
end
def volume_adjustment
super.to_i
end
end
属性
[RW] | local_stored_attributes |