This question already has answers here:
Closed 5 years ago.
Rails order by results count of has_many association
(6个答案)
我有一个Deal模型。我想整理一些交易:
@deals = current_user.deals

他们有多少人。我该怎么做?has_many :clicks当然是一个字段。

最佳答案

我将在counter_cache模型中添加Deal以避免改进数据库查询。有关counter_cache的详细信息,请参见:http://guides.rubyonrails.org/association_basics.html#counter-cache
不仅仅是:

current_user.deals.order(:clicks_count)

# or when deals are already loaded
current_user.deals.sort_by(:clicks_count)

10-08 14:26