Reputation: 18119
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?
Upvotes: 1
Views: 522
Reputation: 1679
ok, I'm assuming that "main" is a named scope of Category and that children is a has_many association. You could add another scope to category, one that retrieves the children of all the categories in one query... Something like:
scope :with_children, includes(:children)
This would cause that instead of making one query per category to retrieve the children it will make only one query to retrieve the children of all the categories you are loading.
Upvotes: 1