Skip to content

Instantly share code, notes, and snippets.

@GertThiel
Created February 17, 2010 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GertThiel/306555 to your computer and use it in GitHub Desktop.
Save GertThiel/306555 to your computer and use it in GitHub Desktop.
module Hobo
module Scopes
class ScopeBuilder
def exists_sql_condition(reflection, any=false)
owner = @klass
owner_primary_key = "#{owner.table_name}.#{owner.primary_key}"
if reflection.options[:through]
join_table = reflection.through_reflection.klass.table_name
owner_fkey = reflection.through_reflection.primary_key_name
conditions = reflection.options[:conditions].blank? ? '' : " AND #{reflection.through_reflection.klass.send(:sanitize_sql_for_conditions, reflection.options[:conditions])}"
if any
"EXISTS (SELECT * FROM #{join_table} WHERE #{join_table}.#{owner_fkey} = #{owner_primary_key}#{conditions})"
else
source_fkey = reflection.source_reflection.primary_key_name
"EXISTS (SELECT * FROM #{join_table} " +
"WHERE #{join_table}.#{source_fkey} = ? AND #{join_table}.#{owner_fkey} = #{owner_primary_key}#{conditions})"
end
else
foreign_key = reflection.primary_key_name
related = reflection.klass
conditions = reflection.options[:conditions].blank? ? '' : " AND #{reflection.klass.send(:sanitize_sql_for_conditions, reflection.options[:conditions])}"
if any
"EXISTS (SELECT * FROM #{related.table_name} " +
"WHERE #{related.table_name}.#{foreign_key} = #{owner_primary_key}#{conditions})"
else
"EXISTS (SELECT * FROM #{related.table_name} " +
"WHERE #{related.table_name}.#{foreign_key} = #{owner_primary_key} AND " +
"#{related.table_name}.#{related.primary_key} = ?#{conditions})"
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment