Created
June 22, 2022 12:10
-
-
Save wemrekurt/04a99c2954beed1882534d794555020d to your computer and use it in GitHub Desktop.
An implementation example of counting included records.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # frozen_string_literal: true | |
| class ApplicationRecord < ActiveRecord::Base | |
| def self.include_counts(assc) | |
| nm = table_name.singularize | |
| joins( | |
| %{ | |
| LEFT OUTER JOIN ( | |
| SELECT b.#{nm}_id, COUNT(*) #{assc}_count | |
| FROM #{assc} b | |
| GROUP BY b.#{nm}_id | |
| ) a ON a.#{nm}_id = #{nm.pluralize}.id | |
| } | |
| ).select("#{nm.pluralize}.*, COALESCE(a.#{assc}_count, 0) AS #{assc}_count") | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment