I have a Library, a Library has many Books.
class Library < ActiveRecord::Base
has_many :book_collectings
has_many :books, through: :book_collectings
How do I use default_scope so that Library.all is ordered based on the number of books the Library has? (Or is there a different approach?)
I would agree with the advice of this accepted answer:
Overriding a Rails default_scope
Avoid default scope if at all possible. Even if you used just a scope, to be performant, I think you’d have to write some SQL which might be kind of a pain and may not be portable. I’d recommend considering a counter cache column. Here’s the appropriate Rails guide reference:
http://guides.rubyonrails.org/association_basics.html#belongs_to-counter_cache
You’ll need to create a migration. See this answer for some sample code:
https://stackoverflow.com/a/1794235/149156
After creating the column, you can then create a scope or class method to order by the book count column.