STI changes among inherited types.

In my models I use STI, like this

Car Model: vehicle.rb

class Vehicle < ActiveRecord::Base end 

Car Model: car.rb

 class Car < Vehicle end 

Tire Model: bus.rb

 class Bus < Vehicle end 

If I create a car, can I somehow change it to a car or a bus?

+6
source share
1 answer

To permanently change 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 type of an object in memory without reloading it from the database, use "becomes, as in

 c1 = c1.becomes(Bus) 
+8
source

Source: https://habr.com/ru/post/893917/


All Articles