ruby-on-rails - Handling Single Table Inheritance with a different column
问题描述
I have the following tables
class Product < ActiveRecord::Base
belongs_to :product_type
self.inheritance_column = :product_type_id
end
class MotorProduct < Product
end
class CarProduct < Product
end
I also have this record in my db
Product table records
#<Product id: 1, product_type_id: 1, company_id: 36, name: "Text Motor Insurancee">
Product Type table records
#<ProductType id: 1, name: "Motor">
#<ProductType id: 2, name: "Car">
When i do MotorProduct.all, it returns empty. This is what my query runs
SELECT "products".* FROM "products" WHERE "products"."product_type_id" IN (0)
which means it wasn't able to map properly the product type id.Not sure how to map it out but basically when i run MotorProduct.all
, i am expecting my query to be
SELECT "products".* FROM "products" WHERE "products"."product_type_id" IN (1).
I know i can easily solve all of this if i add a column called type
and give type the same name MotorProduct
but since the current code had this structure, i am trying to see if i can maintain it somehow.
Any help is appreciated
解决方案
inheritance_column
is supposed to contain class names, not arbitrary integers (emphasis mine):
Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed by overwriting
Base.inheritance_column
).
推荐阅读
- kotlin - Hilt:@DefineComponent dagger.hilt.components.SingletonComponent 缺少父声明
- assembly - 如何在 MPLAB 中进行乘法运算?
- amazon-web-services - 我可以使用不需要身份验证的 aws cli 调用吗?
- java - Java WebFlux/Reactor - 过滤一个 Flux
- > 只有在 Mono 中才能找到的项目
> - module - 如何以编程方式卸载 Prestashop 模块?
- python - 如何对数据框操作进行单元测试?
- javascript - Auto adjusting size for two iframes?
- php - 电报机器人键盘按钮
- excel - 如何在不同的工作簿中使用 excel Marcos 匹配值?
- java - 按多个字段分组并按字段的共同值过滤