Skip to content

Instantly share code, notes, and snippets.

@ippeiukai
Created February 14, 2016 13:30
Show Gist options
  • Save ippeiukai/d558cdac418be1bc47cf to your computer and use it in GitHub Desktop.
Save ippeiukai/d558cdac418be1bc47cf to your computer and use it in GitHub Desktop.
association_exists model plugin for Sequel. Like association_join, allows you to filter dataset with association.
module Sequel
module Plugins
module AssociationExists
module DatasetMethods
def association_exists(association, &block)
_association_exists(association, &block)
end
def association_not_exists(association, &block)
_association_exists(association, negate: true, &block)
end
private
def _association_exists(association, negate: false, &block)
ar = model.association_reflections[association]
parent_table_keys = Array(ar.send(:filter_by_associations_conditions_associated_keys))
association_table_keys = Array(ar.send(:filter_by_associations_conditions_key))
subquery = ar.associated_dataset
subquery = subquery.where(association_table_keys.zip(parent_table_keys))
subquery = subquery.instance_exec(subquery, &block) if block_given?
where(negate ? ~subquery.exists : subquery.exists)
end
end
module ClassMethods
Plugins.def_dataset_methods(self, DatasetMethods.public_instance_methods)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment