Skip to content

Instantly share code, notes, and snippets.

@wemrekurt
Created June 22, 2022 12:10
Show Gist options
  • Select an option

  • Save wemrekurt/04a99c2954beed1882534d794555020d to your computer and use it in GitHub Desktop.

Select an option

Save wemrekurt/04a99c2954beed1882534d794555020d to your computer and use it in GitHub Desktop.
An implementation example of counting included records.
# 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