Monday, January 11, 2010

accepts_nested_attributes_for and sti

I have a site that lets you create child entities on the create form for the aggregate root. Thanks to accepts_nested_attributes_for this isn't too hard.

accepts_nested_attributes_for :kids, :allow_destroy => true

The problem I hit was mixing this with single table inheritance. When the child node is for a derived class, it saves without the 'type' information being set.

It seems the accepts_nested_attributes only creates new instances of the generic base class entity, which then ignores the value passed to the 'type' field.

I ended up doing this work around to get it to replace #new on the base class with an implementation that returns the correctly typed derived instance when the hash passed includes a 'type' field.

Thanks to Coderrr for posting this work around.

Note: I've backed up the code to

GitHub Projects