我有一个Library
,一个Library
有很多Book
s。
class Library < ActiveRecord::Base
has_many :book_collectings
has_many :books, through: :book_collectings
如何使用default_scope
,以便Library.all
根据拥有的书籍数量排序Library
?(或者有不同的方法吗?)
我有一个Library
,一个Library
有很多Book
s。
class Library < ActiveRecord::Base
has_many :book_collectings
has_many :books, through: :book_collectings
如何使用default_scope
,以便Library.all
根据拥有的书籍数量排序Library
?(或者有不同的方法吗?)
我同意这个已接受答案的建议:
尽可能避免使用默认范围。即使您只使用了一个范围,为了提高性能,我认为您必须编写一些 SQL,这可能有点痛苦并且可能不可移植。我建议考虑一个计数器缓存列。这是适当的 Rails 指南参考:
http://guides.rubyonrails.org/association_basics.html#belongs_to-counter_cache
您需要创建迁移。请参阅此答案以获取一些示例代码:
https://stackoverflow.com/a/1794235/149156
创建列后,您可以创建范围或类方法以按图书计数列排序。