Custom serialization for fields in Rails

2020-08-24 07:20发布

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.

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

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

7条回答
迷人小祖宗
2楼-- · 2020-08-24 07:52

We just released a gem (AttributeHelpers) that does exactly this. Disclaimer: I am a maintainer for the gem.

It allows you to call attr_symbol :gender in your class definition and the serialization happens automagically.

查看更多
登录 后发表回答