Forum: Ruby on Rails single table inheritance: change object 'type' after create?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Aaf9d67916c3c07e43a20e5e885f757b?d=identicon&s=25 Asa Hopkins (asa)
on 2006-01-15 01:53
Hey folks,

I'm trying to keep track of couple of different kinds of "entities" in
my rails app: "people", "organizations", and "committees".  I have a
single Entities table in the database, and I'm using Single Table
Inheritance to keep the different subclasses in the same table, with a
field "type".

My problem comes when allowing the user to correct a mistake -- say,
change a "committee" to a more general "organization".
@entity.update_attributes({:type=>"Organization"}) doesn't change the
database.  I can understand that ruby doesn't want me changing the class
of an existing object.  However, is there a way I can make this change,
while keeping the entity's same "id" (so I don't have to change
everywhere that's referenced)?

Thanks a bunch for your help,
Asa
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2006-01-15 04:01
(Received via mailing list)
Asa Hopkins wrote:

> of an existing object.  However, is there a way I can make this change,
> while keeping the entity's same "id" (so I don't have to change
> everywhere that's referenced)?

The STI "type" attribute is protected from mass assignment, so instead
use:

    @entity.update_attribute( :type, 'Organization' )

or

    @entity[:type] = ...
    ...
    @entity.save


--
We develop, watch us RoR, in numbers too big to ignore.
Aaf9d67916c3c07e43a20e5e885f757b?d=identicon&s=25 Asa Hopkins (asa)
on 2006-01-15 05:19
Thanks!  That worked right away.

Asa

Mark Reginald James wrote:
>
> The STI "type" attribute is protected from mass assignment, so instead
> use:
>
>     @entity.update_attribute( :type, 'Organization' )
>
> or
>
>     @entity[:type] = ...
>     ...
>     @entity.save
>
>
> --
> We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.