首页 > 解决方案 > 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

标签: ruby-on-railsrubypostgresqlruby-on-rails-4single-table-inheritance

解决方案


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).


推荐阅读