ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass

mrudult picture mrudult · Jul 26, 2013 · Viewed 37.4k times · Source

I'm newbie to Rails.
I have two models Category and Product as follows:-

class Category < ActiveRecord::Base
 attr_accessible :type

 has_many :products
end

class Product < ActiveRecord::Base
 attr_accessible :category_id, :color, :price, :title

 belongs_to :category
end

And my schema.rb is as follows:-

ActiveRecord::Schema.define(:version => 20130725220046) do

create_table "categories", :force => true do |t|
    t.string   "type"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "products", :force => true do |t|
    t.integer  "category_id"
    t.decimal  "price",       :precision => 10, :scale => 0
    t.string   "title"
    t.string   "color"
    t.datetime "created_at",                                 :null => false
    t.datetime "updated_at",                                 :null => false
  end

end

In Rails console I created two products with two products with the Product.create command

[#<Product id: 1, category_id: 1, price: 500, title: "shirt", color: "blue", `created_at: "2013-07-25 22:04:54", updated_at: "2013-07-25 22:04:54">, #<Product id: 2, category_id: 1, price: 600, title: "tees", color: "black", created_at: "2013-07-25 22:05:17", updated_at: "2013-07-25 22:05:17">]`  

And created two Categories with the Category.create command in console

<Category id: 1, type: "clothing", created_at: "2013-07-25 22:03:54", updated_at: "2013-07-25 22:03:54"><Category id: 2, type: "footwear", created_at: "2013-07-25 22:04:02", updated_at: "2013-07-25 22:04:02">  

Now, Product.all works fine but Category.all gives

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'clothing'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Category.inheritance_column to use another column for that information.

What's wrong in there? I want to make a relationship between Category and Product like
a category has_many products and products belongs_to a category.

Answer

Mike Szyndel picture Mike Szyndel · Jul 26, 2013

type is restricted word, you can't use it as a column name in ActiveRecord models (unless you're doing STI).