rails/rails — pull request #7541 by pivotalcommon (2012-09-06 13:55:59+00:00)
Title: Added customizable STI type serialization.

Rails will store the name of a child class in the database to use for re-instantiating the record as the correct class later. By specifying an `inheritance_serializer` and `inheritance_deserializer`, you can customize the stored identifier.

This is primarily useful for working with legacy data models.

```ruby
class Foo < ActiveRecord::Base
self.inheritance_serializer = ->(klass) do
# Map the class to the appropriate type identifier.
# Defaults to `klass.name`.
if klass == Child1
1
elsif klass == Child2
2
end
end

self.inheritance_deserializer = ->(type_before_cast) do
# Map the type identifier back into the appropriate class.
# Defaults (approximately) to `type_before_cast.constantize`.
case type_before_cast.to_i
when 1
Child1
when 2
Child2
end
end
end

class Child1 < Foo; end
class Child2 < Foo; end
```