继承类型之间的 STI 变化. [英] STI change amongs inherited types.

查看:31
本文介绍了继承类型之间的 STI 变化.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中,我像这样使用 STI

In my models I use STI like this

车辆型号:vehicle.rb

Vehicle Model: vehicle.rb

class Vehicle < ActiveRecord::Base
end

车型:car.rb

class Car < Vehicle
end

总线型号:bus.rb

Bus Model: bus.rb

class Bus < Vehicle
end

如果我创建了一辆汽车,我可以以某种方式将其类型更改为车辆或巴士吗?

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

推荐答案

要永久更改类型,请更改 type 列的值.

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

要在不从数据库重新加载的情况下更改内存中的对象类型,请使用becomes, as in

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

c1 = c1.becomes(Bus)

这篇关于继承类型之间的 STI 变化.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆