Models that reference themselves

Hi

I’m pretty much a newbie to Rails and I have at least two projects
under development that are going to need the same type of constructs
and I’m struggling to get my head around how to achieve what I want
using Rails models and relationships.

In one project I have a hierarchy of (geographical) sites. For
example:

Earth
Europe
Ireland
Cork
Kerry
Galway

UK
France
America

If I were using any other language my sites model would look like:

id, # Primary Key
site_name,
parent_id # references the id of this site’s parent.

In Rails I think I need to:

  1. Drop the parent_id column
  2. Use a bridge table to bridge the site id back to the parent site
    record and
  3. A has_and_belongs_to_many relationship

Is this the correct approach?

I’m sure this must have been done before as I have two projects that I
want to do the same thing in. I’ve found examples in the wiki of
bridging two tables in this way; but I’ve not found a way of linking a
table back to itself.

Any assistance will be gratefully appreciated.

Regards

David

On 12 Oct 2007, at 11:39, DavidH wrote:

  1. Use a bridge table to bridge the site id back to the parent site
    record and
  2. A has_and_belongs_to_many relationship

Is this the correct approach?

If a site has only one parent then you should stick with parent_id.

You then stick
belongs_to :parent, :class_name => ‘Site’, :foreign_key => ‘parent_id’

in your Site model

Fred

Many thanks Frederick. Yes a site can only have one parent. I will
give your suggestion a try and see how I get on.

Cheers

David

On Oct 12, 12:13 pm, Frederick C. [email protected]

On 10/12/07, Frederick C. [email protected] wrote:

In Rails I think I need to:
You then stick
belongs_to :parent, :class_name => ‘Site’, :foreign_key => ‘parent_id’

in your Site model

May also want to add:
has_many :children, :class_name =>“Site”, :foreign_key => “parent_id”

You could also look at acts_as_tree, acts_as_nested_set and various
other plugins for managing hierarchic data structures.

Isak