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中完成.要序列化的对象必须回复load和dump方法.
以下是在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
| 归档时间: |
|
| 查看次数: |
8391 次 |
| 最近记录: |