Self-Referential ActiveRecord

ruby rails active_record

Tue Apr 14 11:46:43 -0700 2009

Migrating a legacy bulletin board system based on Perl/CGI to Rails (2.2.2). I am doing this as BDD with cucumber & rspec goodness and I’ll be posting my travails on BDD pretty soon.

Anyhow, to the meat of this post, you need to know how your database schema for the bulletin board system is going to scaffold first before you start writing scenarios/stories to conform to your schema. To that end, I came across the need to implement a threaded bulletin board messages structure, ala reddit comments. This is obviously nothing new but it’s noteworthy of a blog post for my own future reference as well and hopefully whoever reading this as well.

There are some security setup for the bulletin boards as well, but for a threaded setup, this excerpt below should suffice:

class BulletinBoard < ActiveRecord::Base
  belongs_to :quester
  has_many :bulletin_board_topics
  has_many :bulletin_board_messages, :through => :bulletin_board_topic
end

class BulletinBoardTopic < ActiveRecord::Base
  belongs_to :quester
  belongs_to :bulletin_board
  has_many :bulletin_board_messages
end
	
class BulletinBoardMessage < ActiveRecord::Base
  belongs_to :bulletin_board_topic
  belongs_to :quester
  has_many :child_nodes, :foreign_key => 'parent_node_id', 
                         :class_name => 'BulletinBoardMessageThread',
                         :dependent => :destroy
end

class BulletinBoardMessageThread < ActiveRecord::Base
  belongs_to :parent_node, :class_name => "BulletinBoardMessage"
  belongs_to :child_node, :class_name => "BulletinBoardMessage"
end

I think the structure is pretty self-explanatory. One may be confused about what a quester is, as a gaming project, a quester is essentially a user in our system.

blog comments powered by Disqus