Tricky helper question

I am trying to code a helper that will print a list of threaded forums,
as options of a select field…a forum has a parent_id (which is another
forum’s id) or 0, meaning it is a “root level” forum…

For example, the result will look like:

Forum 1
–Sub forum 1
–Sub forum 2
----Sub Sub Forum 1
–Sub forum 3
Forum 2
–Sub forum 2a

(picture this in a select menu)

There can be an unlimited amount of nested forums…my first thought was
to use a recursive function, however, since an helper will only “print”
what it returns (and should only return 1 thing) it’s a bit tricky… I
don’t really see an easier way to this, but anyway here’s what I have so
far:


def print_child_forums(master)
#get the forum’s childs…
childs = Forum.find(:all, :conditions => [“parent_id = ?”,
master.id], :order => ‘name ASC’)

if childs.size > 0 #forum has subforums
  #Here, I need to print this forum before going deeper!
  for child in childs
    print_child_forums(child)
  end

else
    #forum has no child, print it...
    "<option value=\"#{master.id}\">#{master.name}</option>"
end

end

The problem obviously is that when a forum has child, it is never
printed! since the only “return point” of the function occurs when the
forum has no child… from what I understand, I can’t output any html in
the helper function, except with it’s return value… and I can’t really
use string concatenation since the function is being called multiple
times (recursivity)…

my idea basically(using pseudo code) was quite simple:

print_childs(master):
if master has childs
print master
for each child:
print_childs(child) (recursivity)
end for
else (master has no child)
print master
end if master has childs
end print_childs

But this is turning out to be trickier than I thought… Note that I
might be going at it all wrong, it’s 5am+ and I’m trying to get this
done before going to bed…and somehow, I doubt I am thinking clearly
LOL…

Any suggestions would be appreciated!

use partials instead
partials can be recursive and can take arguments by :locals or
:collection

Awesome! Got it to work by using a “recursive” partial :slight_smile:

Thanks a lot!

Thorsten M. wrote:

use partials instead
partials can be recursive and can take arguments by :locals or
:collection

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs