Created
February 14, 2016 13:30
-
-
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.
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 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