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