因此,我有以下内容:
class Product < ActiveRecord::Base
# Has a bunch of common stuff about assembly hierarchy, etc
end
class SpecializedProduct < Product
# Has some special stuff that a "Product" can not do!
end
在制造和装配过程中,会捕获有关产品的数据。在捕获时,最终的产品类型未知。在数据库中创建产品记录后(也许几天后),可能有必要将该产品转换为专用产品并填写其他信息。但是,并非所有产品都会变得特化。
我一直在尝试使用以下内容:
object_to_change = Product.find(params[:id])
object_to_change.becomes SpecializedProduct
object_to_change.save
然后,当我执行
SpecializedProduct.all
时,结果集不包括object_to_change
。而是object_to_change
仍在数据库中列为Product
UPDATE "products" SET "type" = ?, "updated_at" = ? WHERE "products"."type" IN ('SpecializedProduct') AND "products"."id" = 30 [["type", "Product"], ["updated_at", Fri, 17 May 2013 10:28:06 UTC +00:00]]
因此,在调用
.becomes SpecializedProduct
之后,.save
方法现在使用正确的类型,但是由于更新的WHERE
子句过于具体,因此无法更新记录。我真的需要直接访问模型的
type
属性吗?我真的不愿意。 最佳答案
查看becomes
和becomes!
的源代码,它不会使原始对象发生变异。您需要将其分配给新变量:
some_product = Product.find(params[:id])
specialized_product = some_product.becomes SpecializedProduct
specialized_product.save
但是,不确定该如何处理记录的主键,因此您可能需要进行一些其他处理,以确保您的关系不会受到影响。
关于ruby-on-rails - Rails中的STI : How do I change from a superclass to a subclass without accessing the “type” attribute directly?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16655543/