Rails 中字段的自定义序列化 [英] Custom serialization for fields in Rails

查看:36
本文介绍了Rails 中字段的自定义序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法对 rails 中的字段进行自定义序列化,这是一种在保存和加载字段时运行的方法,用于从/转换为最终保存在数据库中的字符串.

Is there a way to have a custom serialization for fields in rails, a method that runs when a field is saved and loaded to convert from/to a string which is what ultimately is saved on the database.

特别是我想要做的是有一个像性别这样的类型符号的字段,可能的值是 :male 和 :female 在数据库中存储male"和female".有一些解决方法,例如:

Specifically what I want to do is have a field of type symbol like gender, with possible values :male and :female storing "male" and "female" on the database. There are some workarounds, like:

def gender
  read_attribute(:gender).try(:to_sym)
end

但这会使 obj.attributes 保持不变,因此这是一个有漏洞的抽象.

but that leaves obj.attributes unchanged, so it's a leaky abstraction.

推荐答案

您可以在 Rails 3.1 中完成.要序列化的对象必须回复loaddump 方法.

You can do it in Rails 3.1. The object you want to serialize has to reply to load and dump methods.

这是一个在 Base64 中序列化字符串的示例.

Here is an example of serializing a string in Base64.

class User < ActiveRecord::Base
  class Base64
    def load(text)
      return unless text
      text.unpack('m').first
    end

    def dump(text)
      [text].pack 'm'
    end
  end

  serialize :bank_account_number, Base64.new
end

更多详情参见:http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2011/03/09/custom-activerecord-attribute-serialization/index.html

这篇关于Rails 中字段的自定义序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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