--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
Thanks.
> Grandpa has one to many kids and has one paNo, Grandpa has_many pas
I didnt quite get how you proposed listing the pas (and kid count for
each pa) that belong to a certain grandpa
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
A crude way (untested), I am sure there are better as I suspect this
will call count zillions of times. It should get you going and you
can refactor when you want to.
grandpa.pas will give you an array of pas, then simply sort this array
by the number of kids.
sorted = grandpa.pas.sort_by { |p| p.kids.count }
Colin
Your solution may certainly work... but is a bit "imperative" in
coding terms, and does introduce an n+1 problem.
Rails offers a feature called "counter_cache" on associations - which
gives you a column in associate keeping track of the amount of
"belonging" records.
Have a look for it in the manual here:
http://rails.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
If you use it, you can then just do a normal find without the block
and order by the counter-cache column, which avoids all the extra SQL
counts.