Skip to content

Instantly share code, notes, and snippets.

@bigfive
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save bigfive/9064325 to your computer and use it in GitHub Desktop.

Select an option

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

nocache commented Feb 18, 2014

Copy link
Copy Markdown

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

@bigfive

bigfive commented Feb 18, 2014

Copy link
Copy Markdown
Author

Nice catch

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