Forum: Ruby on Rails How to change class of an STI object?

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.
C47b402b094e734c9e1ad17086bb1209?d=identicon&s=25 bbebop (Guest)
on 2007-03-27 10:51
(Received via mailing list)
I have some models which use the same table via single table
inheritance. I (think I) need to change objects from one class to
another and not sure how to go about that.

Consider these models:

  class Project < ActiveRecord::Base
  end

  class Goal < Project  # inherits project characteristics
  end

  class Assignment < Project  # inherits project characteristics
  end

They are distinguished from each other by the 'type' column.

  class CreateProjects < ActiveRecord::Migration
    def self.up
      create_table :projects do |t|
        t.column :type, :string
        ...
      end
    end
  end

How would I convert a 'Project' object into a 'Goal' object while
preserving other characteristics (id, title, etc.)?

Thanks!
588ab1c0a5610a7e160a3b101abb91e6?d=identicon&s=25 MichaelLatta (Guest)
on 2007-03-27 17:53
(Received via mailing list)
Just change the value in the type column to change the type to any of
the other types.  I define a method that aliases to type to make it
easier to access.  You will need to reload the data to get a different
Ruby object.

Michael
C47b402b094e734c9e1ad17086bb1209?d=identicon&s=25 bbebop (Guest)
on 2007-03-27 19:24
(Received via mailing list)
Thanks Michael. That's simple enough!
This topic is locked and can not be replied to.