Rails中字段的自定义序列化
有没有办法为rails中的字段进行自定义序列化,这是一种在保存字段并加载以从/转换为最终保存在数据库中的字符串时运行的方法。
具体来说,我想做的是有一个类型符号的字段,如性别,可能的值:男性和女性在数据库中存储“男性”和“女性”。 有一些解决方法,例如:
def gender read_attribute(:gender).try(:to_sym) end
但是这使得obj.attributes保持不变,所以它是一个漏洞的抽象。
你可以在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
有关详细信息,请参阅: http : //archives.edgerails.info/articles/what-s-new-in-edge-rails/2011/03/09/custom-activerecord-attribute-serialization/index.html
def whachamacallit read_attribute("whachamacallit").to_sym end def whachamacallit=(name) write_attribute("whachamacallit", name.to_s) end
将它们存储在数据库中作为stings,但在将它们拉出时将它们提取为符号,然后在保存之前将其转换回来。 可以使用任何数字或字符串/符号的组合。
将其限制为只有少数几个
validates_inclusion_of :whachamacallit, :in => [ :male, :female, :unknown, :hidden ]
来自http://blog.quov.is/2012/05/01/custom-activerecord-attribute-serializers/
class Recipe < ActiveRecord::Base serialize :ingredients, IngredientsList end class IngredientsList < Array def self.dump(ingredients) ingredients ? ingredients.join("\n") : nil end def self.load(ingredients) ingredients ? new(ingredients.split("\n")) : nil end end
你可以为模型定义模型to_xml,它会做到这一点http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html
它可以定义Marshall.dump并以我认为的方式放入,但它需要调查
您可以在模型中使用serialize
方法。 请参考此链接: http : //api.rubyonrails.org/classes/ActiveRecord/Base.html (ps。在该页面中搜索关键字“序列化”; D)
简而言之,你可以这样做:
class YourModel < ActiveRecord::Base serialize :db_field end
在保存到数据库之前,Rails会自动序列化字段,并在从数据库中获取后对其进行反序列化。
只有男性/女性你可以做一个像男性的布尔列,如果它是假的,假设这意味着女性,为它添加包装方法
def female? return !self.male? end
我们刚刚发布了一个确实如此的gem( AttributeHelpers )。 免责声明:我是gem的维护者。
它允许您在类定义中调用attr_symbol :gender
,并且序列化自动发生。