Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STI change amongs inherited types.

In my models I use STI like this

Vehicle Model: vehicle.rb

class Vehicle < ActiveRecord::Base
end

Car Model: car.rb

class Car < Vehicle
end

Bus Model: bus.rb

class Bus < Vehicle
end

If I create a Car can I somehow change it's type to Vehicle or Bus?

like image 547
Immo Avatar asked Jul 29 '11 23:07

Immo


1 Answers

To permanently alter the type, change the value of the type column.

c1 = Car.first
c1.name # BMW

c1.update_attribute(:type, "Bus")

b1 = Bus.first
b1.name # BMW

To also change the object type in-memory without reloading it from the DB, use "becomes, as in

c1 = c1.becomes(Bus)
like image 78
Harish Shetty Avatar answered Oct 17 '22 04:10

Harish Shetty