Is possible to order a nested model?

Hey,

the problem everyone seems to be having here is forgetting that this is a recursive data structure.

Assuming each category has a parent_id field, and assuming that root categories have a parent_id which is nil, this should work:

in category.rb:

def self.options_for_select(records = nil)
   records ||= find(:all, :order => 'name ASC')
   records_by_parent = records.group_by(&:parent_id)

   collector = lambda do |memo, category|
     memo << ['*' * category.depth + category.name, category.id]
     Array(records_by_parent[category.id]).inject(memo, &collector)
   end

   records_by_parent[nil].inject([], &collector)
end

Regards,
Trevor

Hey,

see below:

Trevor Squires wrote:

def self.options_for_select(records = nil)
   records ||= find(:all, :order => 'name ASC')
   records_by_parent = records.group_by(&:parent_id)
   collector = lambda do |memo, category|
     memo << ['*' * category.depth + category.name, category.id]
     Array(records_by_parent[category.id]).inject(memo, &collector)
   end
   records_by_parent[nil].inject([], &collector)
end

Perfect :slight_smile:
but just one thing, about performance...if there're a lot of people that are loading the page i think it'll be a problem, what do you think?
i think that it's better order them when are inserted into the db (also because it's done just once, or eventually not so much frequently), so it's possible to get all the list order just by one select and no operations, instead of order all for each request

I prefer not to speculate on whether it'll be a performance 'problem' - performance is something that can really only be determined by measuring on relevant hardware with relevant tests.

There's often knee-jerk reactions to your question (which are often right) such as "use fragment caching". However, my attitude is: if you can figure out a way to hyper-optimize it today, you can certainly figure out how to hyper-optimize the day a real issue emerges to prove *this* is the best place to spend your time trying to speed things up.

If it works and it's not a screaming obvious performance issue (like 10 second page load times) then just move on, you're done and you've probably got better things to do.

Oh, and if you really can't let it go and you just *have* to try and optimize this... then just "use fragment caching" :slight_smile:

Trevor