Skip to content

Instantly share code, notes, and snippets.

@sumskyi sumskyi/README.md
Last active Oct 11, 2019

Embed
What would you like to do?
rails STI with custom "type" field and storing there value different from ClassName

GeoEntity.last

SELECT geo_entities.* FROM geo_entities ORDER BY geo_entities.id DESC LIMIT 1

returns:

County id: 4, eid: nil, pid: nil, ename: nil, etype: 2, created_at: "2011-11-21 06:26:37", updated_at: "2011-11-21 06:26:37"

class City < GeoEntity
end
class County < GeoEntity
end
class GeoEntity < ActiveRecord::Base
set_inheritance_column :etype
ENTITIES = {
1 => GeoEntity::State,
2 => GeoEntity::County,
3 => GeoEntity::City,
4 => GeoEntity::Zip
}
class << self
def find_sti_class(type_name)
ENTITIES[type_name.to_i] or super
end
def sti_name
ENTITIES.invert[self]
end
end
end
class State < GeoEntity
end
class Zip < GeoEntity
end
@felixbuenemann

This comment has been minimized.

Copy link

felixbuenemann commented Aug 18, 2012

Thanks for sharing, I have a similar case, where the legacy db stores the sti value in uppercase – will be easy to adapt.

@lanvige

This comment has been minimized.

Copy link

lanvige commented May 10, 2014

There was an issue, if you want build a entity in one to many reference like

model.geo_entities.create(
...
)

RuntimeError (Circular dependency detected while autoloading constant GeoEntity):

Do you have a solution?

@vamdt

This comment has been minimized.

Copy link

vamdt commented Sep 3, 2014

i moved the state code to itself's class
https://gist.github.com/vamdt/75aca125883a88a9f1fd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.