Sunday, September 11, 2011

Re: [Rails] How to recursively count threads belonging to a chain of forums

On 11 September 2011 23:10, David Roy <lists@ruby-forum.com> wrote:
> Hi I am trying to count all the threads that belong to a forum right
> though the chain.
>
> 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
   sub_forums.inject(threads.count) { |memo, sub_forum| memo +=
sub_forum.count_threads }
 end
> end

That should recurse through all the sub-forums... make sure you don't
nest an upper forum in one of the children because you'll get a stack
overflow :-)

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate