views:

36

answers:

0

My goal is to print a json document with the structure described in the chosen answer on this thread. I only have one level of sub categories (2 total, including root) so it should be a little bit easier than the problem there. The problem I'm having is with efficiency. With only ~20 root categories the recursion is causing my script to act very slowly. My controller looks like this:

def categories
    render :text => "var categories = #{Category.main.map { |c| c.with_children }.to_json};"
end

And the respective method on the Category model:

def with_children
    {
        :name => self.name, 
        :id => self.id, 
        :parent_id => self.parent_id, 
        :children => self.children.blank? ? nil : self.children
    }
end

Can anyone offer some advice to making this process more efficient? Maybe eager loading or something?