views:

73

answers:

0

I have a many-to-many relation between labels and files (using rails). The labels model is also a nested set (awesome nested set plugin) that allows the lables to be organized in a hierarchy like:

  • Multimedia
    • Video
      • mpeg-4
      • h264
      • theora
    • Audio
      • mp3
      • aac
      • vorbis

To access all the files under the Video label I would have to create some sort of recursive method that would be called recursively over each child of the Video label storing the files in an array:

def get_files_recursively(label)
   files = label.files
   label.children.each { |child|
     files << child.files
   }
   return files.flatten
end


label = Label.find_by_name("Video")
video_files = get_files_recursively(label)

I haven't tested this but I guess this is not efficient at all so I was wondering if there is a single SQL query I can issue to get the same result? Ah and since each file can be under several labels the result must avoid all duplicates.