0
class Forum::Forum < ActiveRecord::Base
  belongs_to :parent_forum, :class_name => "Forum"
  has_many :sub_forums, :class_name => "Forum", :foreign_key => :parent_id
  has_many :threads

  def count_threads
    threads.count
  end
end

Hi I am trying to count all the threads that belong to a forum right though the chain. Currently it counts the threads that belong to the forum you're on, so if you're on forum id 1 it will count threads that belong to forum id 1 only, however forum id 1 also has sub_forums such as forum id 4 which also has a sub_forum with a id of 8 and this could go on forever.

I would really appreciate some help here, I have grand plans to build my site in rails instead of zend framework but a few little snags are keeping me stuck sometimes.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Cabbit
  • 1

1 Answers1

1

I'd recommend taking a look at Ancestry. You should be able to get everything you need out of there if your model is what I think it is, and it can save you some code.

I believe something like @record.descendants.count should do the trick once you've integrated it.

Kristian PD
  • 2,705
  • 1
  • 19
  • 22
  • I wish to stick to a vanilla rails solution. – Cabbit Sep 11 '11 at 21:01
  • In that case I believe you're going to need to recurs through your associations in order to find all children/children of children/etc. I haven't read it in depth, but this may give you some ideas for more efficient layout of your tables: http://stackoverflow.com/questions/935098/database-structure-for-tree-data-structure – Kristian PD Sep 12 '11 at 16:20