默认的ActiveRecord的迁移连载专栏 [英] default for serialized column in activerecord migration

查看:95
本文介绍了默认的ActiveRecord的迁移连载专栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个序列化列:尺寸,并在我的移民,我想设置字段设置为默认的哈希值

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的序列化的哈希保存在数据库中,它的作用是将其转换为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的迁移连载专栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆