single table inheritence

Another question about single table inheritance.

class PostType < ActiveRecord::Base end

class MainType < PostType end

class SubType < MainType belongs_to :parent_type, :class_name => ‘SubType’, :foreign_key =>

:parent_id end

Ok, my initial question is: are you trying to do one level categorization such as:

 Parent Type

class PostType < ActiveRecord::Base

belongs_to :parent, :class_name => ‘PostType’, foreign_key => ‘parent_id’ has_many :sub_post_types, :class_name => ‘PostType’ end

p = PostType.new p.save

subp = PostType.new subp.parent = p subp.save subp2 = PostType.new subp2.parent = p subp2.save

p.sub_post_types will return [subp, subp2] subp.parent will return p subp2.parent will return p

And in your migration you would need

create_table :post_types do |t| t.column :parent_id, :int t.column :type_name, :string end

This sets it up, actually, the second way I mentioned, but you can just use it as the first if you want.

Any given PostType will have a parent as post_type.parent and any given PostType can have as many children as it wants, accessible via post_type.sub_post_types

Is this what you need?

I’m sorry, I forgot a very important part (shows what I get for not testing my code before I gave it to you) The line has_many :sub_post_types, :class_name => ‘PostType’ should instead be

has_many :sub_post_types, :class_name => ‘PostType’, :foreign_key => ‘parent_id’

That should fix it.

Yeah… what it’s doing (in case you’re curious): When you tell the belongs_to line that it’s foreign_key is parent_id, that means that when you set a parent, it sets parent_id to the id of the parent. Then, when you call something like ( p.sub_post_types), what it’s generating behind the scenes is SELECT * from post_types where post_types.sub_post_type_id = #{self.id} In order to change that query to use post_types.parent_id instead of post_types.sub_post_type_id, you set the foreign key.

If I understand what you’re asking, then: right!