overstimulate

Implimenting childNodes & parentNode in node model

Wed, 07 Dec 2005 comments

Assume your Ruby on Rails app needs a nodes model with which to build trees of nodes (forests technically since we do not restrict to one root.) So you build your database schema:

CREATE TABLE nodes (
    id serial NOT NULL,
    name character varying(100) NOT NULL,
    node_id integer
);

Then you your model contains the lines:

class Node < ActiveRecord::Base
  has_many   :nodes   # children method
  belongs_to  :node   # parent method
end

This works great - except you end up with ugly code like:

  @node = Node.find 123
  @node.nodes.first.node # identity

The difference between asking for the parent and child nodes is one character "s" - Typos and misunderstandings! Let us modify the model to provide a better interface to the related nodes:

class Node < ActiveRecord::Base
  has_many   :childNodes,  :class_name=>'Node'
  belongs_to :parentNodes, :class_name=>'Node'
end

Now we can have the less terse but more readable:

  @node = Node.find 123
  @node.childNodes.first.parentNode

The :class_name parameter to the has_many function is very helpful. No more models that are just placeholders. Another example - a car is owned by one person, and might have many riders. All those people are instances of the User model.

class Car < ActiveRecord::Base
  has_one    :owner,  :class_name=>'User'
  belongs_to :riders, :class_name=>'User'
end

Use :associated_foreign_key and :foreign_key for even more clarity at the database level (owner_id instead of user_id, parent_id instead of node_id)


Responses to "Implimenting childNodes &amp; parentNode in node model"

Leave a response

My Card Add to your Address Book

Jesse Andrews
open source, web browsers, web services, web sites & folk dancing. contacts/sites

Keep Up To Date

Get updates via RSS or
get email when I blog

Previous Blog Posts