Skip to content

Instantly share code, notes, and snippets.

@bigfive
Last active August 29, 2015 13:56
Show Gist options
  • Save bigfive/9064325 to your computer and use it in GitHub Desktop.
Save bigfive/9064325 to your computer and use it in GitHub Desktop.
count_sql_for
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)
clas Bar < ActiveRecord::Base
scope :no_foos, lambda{ joins(:foos).where("(#{count_sql_for(:foos)}) = 0") }
end
@nocache
Copy link

nocache commented Feb 18, 2014

you don't need to call #to_s inside the string interpolation. It will call it implicitly on a symbol.

@bigfive
Copy link
Author

bigfive commented Feb 18, 2014

Nice catch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment