Created
February 17, 2010 12:28
-
-
Save GertThiel/306555 to your computer and use it in GitHub Desktop.
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 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