Forum: Ruby on Rails Converting STI objects

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Eb778b8bb642aa8a82c2b8b63705b6af?d=identicon&s=25 Jean-Etienne Durand (jetienne)
on 2007-05-02 13:51

Check the following data model:
class BaseClass < ActiveRecord::Base; end
class Class1 < BaseClass; end
class Class2 < BaseClass; end

For some reasons, I would like to "convert" a Class1 object to a Class2
Creating a new Class2 object from Class1 object is not a solution, since
Class1 object is associated to lots of objects and I do not want to
recreate the associations.

obj = BaseClass.find(<id>)
=> how to cast obj from Class1 to Class2

Thank you!
3a0f2ec009ceffdd65f056540a409a23?d=identicon&s=25 Chris Mear (Guest)
on 2007-05-02 14:16
(Received via mailing list)
One way is to manually set the type column:

obj[:type] = Class2


On May 2, 12:51 pm, Jean-Etienne Durand <rails-mailing-l...@andreas-
9a71df6388c8d37bfdf0e18742ea944a?d=identicon&s=25 AndyV (Guest)
on 2007-05-06 19:58
(Received via mailing list)
You might need to use update_attribute to avoid validation checking on

BaseClass.find(<id>).update_attribute(:type, Class1)
This topic is locked and can not be replied to.