Last active
August 29, 2015 13:56
-
-
Save bigfive/9064325 to your computer and use it in GitHub Desktop.
count_sql_for
This file contains 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
module AssociationCounter | |
def count_sql_for(association_sym) | |
association_table_name = reflect_on_association(association_sym).klass.table_name | |
select("count(#{association_table_name}.id) as #{association_sym}_count").joins(association_sym).to_sql | |
end | |
end | |
ActiveRecord::Base.send(:extend, AssociationCounter) |
This file contains 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
clas Bar < ActiveRecord::Base | |
scope :no_foos, lambda{ joins(:foos).where("(#{count_sql_for(:foos)}) = 0") } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you don't need to call #to_s inside the string interpolation. It will call it implicitly on a symbol.