Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom serialization for fields in 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.

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.

like image 363
pupeno Avatar asked Dec 17 '10 16:12

pupeno


2 Answers

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

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

For more details see: http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2011/03/09/custom-activerecord-attribute-serialization/index.html

like image 144
Maciej Biłas Avatar answered Oct 17 '22 12:10

Maciej Biłas


def whachamacallit
  read_attribute("whachamacallit").to_sym
end
def whachamacallit=(name)
  write_attribute("whachamacallit", name.to_s)
end

store them as stings in the database, but extract them as symbols when you pull them out then convert back before you save. would work with any number or combination of strings / symbols.

to limit it to only a select few

validates_inclusion_of :whachamacallit, :in => [ :male, :female, :unknown, :hidden ]
like image 4
loosecannon Avatar answered Oct 17 '22 11:10

loosecannon