问题描述
所以我有一个序列化列 :dimensions,在我的迁移中,我想将该字段设置为默认哈希.
so i have a serialized column :dimensions, and in my migration, i would like to set the field to be a default hash.
我试过了……
create_table :shipping_profiles do |t|
t.string :dimensions_in, :default => {:width => 0, :height => 0, :depth => 0}
只是
t.string :dimensions_in, :default => Hash.new()
但字段最终为空.如何在创建时为此字段设置默认序列化对象,或者至少确保我的序列化属性始终是哈希?
but the fields end up null. how can i set a default serialized object for this field on creation, or at least make sure my serialize attribute is always a hash?
推荐答案
当Rails 序列化一个hash 以保存在db 中时,它所做的只是将它转换为YAML 以便它可以存储为一个字符串.要让它在迁移中工作,您需要做的就是将哈希转换为 yaml...
When Rails serializes a hash to save in the db, all it does is convert it to YAML so that it can be stored as a string. To get this to work in the migration, all you need to do is convert the hash to yaml...
t.string :dimensions_in, :default => {:width => 0, :height => 0, :depth => 0}.to_yaml
或者,或者,在初始化后将其设置在模型中...
Or, alternatively, set it in the model after initialization...
class ShippingProfile < ActiveRecord::Base
after_initialize :set_default_dimensions
private
def set_default_dimensions
self.dimensions_in ||= {:width => 0, :height => 0, :depth => 0}
end
end
这篇关于activerecord 迁移中序列化列的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!