STI change amongs inherited types.

2020-07-11 05:39发布

问题:

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?

回答1:

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)