Rails中字段的自定义序列化

pup*_*eno 9 ruby serialization ruby-on-rails

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

具体来说,我想做的是有一个类型符号的字段,如性别,可能的值:男性和女性在数据库中存储"男性"和"女性".有一些解决方法,例如:

def gender
  read_attribute(:gender).try(:to_sym)
end
Run Code Online (Sandbox Code Playgroud)

但是这使得obj.attributes保持不变,所以它是一个漏洞的抽象.

Mac*_*łas 10

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

以下是在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
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅:http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2011/03/09/custom-activerecord-attribute-serialization/index.html

  • 不幸的是,细节链接现在似乎已经死了.您有没有理由将`dump`和`load`定义为实例方法,并将新实例传递给`serialize`?而不是将它们定义为类方法并将类传递给`serialize`?只是想了解,谢谢! (3认同)