1
A
回答
2
生命是如此容易得多counter_cache:
$ rails g migration add_group_member_counts_to_groups
# migration
def change
add_column :groups, :group_members_count, :integer, default: 0
end
class GroupMember < ActiveRecord::Base
belongs_to :group, counter_cache: true
end
class Group < ActiveRecord::Base
has_many :group_members
scope :order_by_group_members_count, order('group_members_count DESC')
end
Group.order_by_group_members_count # => What you're looking for
只有一個查詢,僅在組表。
編輯
如果您需要重置group_members_count:
ids = Group.select(:id).map &:id
ids.each do |id|
Group.reset_counters(id, :group_members)
end
(因爲reset_counters不採取一組ID)
在未來Rails 3.2.0,你會寫:
ids = Group.pluck(:id)
我迫不及待;-)
+0
謝謝,但由於各種原因,我現在想避免這種情況。這怎麼可以用Rails完成?謝謝 – AnApprentice
+0
+1有用的reset_counters代碼 - 也不知道「拔」 - 很好。 –
0
class Group < ActiveRecord::Base
has_many :group_members
default_scope order('(select count(1) from group_members where group_members.group_id = groups.id) desc')
end
請注意,這造成您的訂單子句中的子查詢,這可能會產生許多組記錄一個顯著SQL放緩。如果經常使用這些信息,那麼Delba建議使用計數器緩存可能會更好。
相關問題
- 1. rails 3查詢嵌套資源計數
- 2. Rails的ActiveRecord查詢排序2模型?
- 3. Rails嵌套模型
- 4. 查詢嵌套計數
- 5. 嵌套計數查詢
- 6. MySQL嵌套查詢計數
- 7. 對來自鄰接模型的非嵌套數據數組排序
- 8. ActiveRecord:一種複雜的查詢嵌套關聯和排序
- 9. 根據數組順序排序rails查詢
- 10. Rails的嵌套查詢
- 11. Rails的嵌套SQL查詢
- 12. Django根據父母模型的日期對模型進行排序的查詢
- 13. ActiveRecord的查詢過濾嵌套模型
- 14. 根據參數排序Rails
- 15. 根據從外部查詢派生的字段來計數條目的select語句中的嵌套查詢
- 16. VueJS嵌套數據模型
- 17. HBASE嵌套數據模型
- 18. Ember數據嵌套模型
- 19. Oracle排序嵌套查詢和rownum
- 20. Rails/Postgres嵌套JSON查詢
- 21. 嵌套實體模型查詢問題
- 22. 計數和排序根據在Django查詢列值
- 23. 跨表的嵌套集模型計數
- 24. 嵌套模型的計數總和
- 25. Rails的查詢/範圍:根據加入模型的屬性排除對象
- 26. 爲嵌套的SQL查詢計數
- 27. Rails設計模型不是以嵌套形式保存模型?
- 28. C#和LINQ:按嵌套查詢的值排序查詢
- 29. 模型的Mongoose嵌套查詢引用模型的字段
- 30. SQL嵌套查詢計算
任何任何想法? – AnApprentice