diff --git a/lib/composite_primary_keys/associations.rb b/lib/composite_primary_keys/associations.rb index a95d767..3bcbb30 100644 --- a/lib/composite_primary_keys/associations.rb +++ b/lib/composite_primary_keys/associations.rb @@ -376,31 +376,37 @@ module ActiveRecord::Associations return conditions end - def construct_joins(custom_joins = nil) + def construct_joins(custom_joins = nil) polymorphic_join = nil if @reflection.through_reflection.options[:as] || @reflection.source_reflection.macro == :belongs_to reflection_primary_key = @reflection.klass.primary_key source_primary_key = @reflection.source_reflection.primary_key_name + if @reflection.options[:source_type] + polymorphic_join = "AND %s.%s = %s" % [ + @reflection.through_reflection.table_name, "#{@reflection.source_reflection.options[:foreign_type]}", + @owner.class.quote_value(@reflection.options[:source_type]) + ] + end else reflection_primary_key = @reflection.source_reflection.primary_key_name source_primary_key = @reflection.klass.primary_key if @reflection.source_reflection.options[:as] polymorphic_join = "AND %s.%s = %s" % [ @reflection.table_name, "#{@reflection.source_reflection.options[:as]}_type", - @owner.class.quote_value(@reflection.through_reflection.klass.name) - ] - end - end - - "INNER JOIN %s ON %s %s #{@reflection.options[:joins]} #{custom_joins}" % [ - @reflection.through_reflection.table_name, - composite_join_clause( - full_keys(@reflection.table_name, reflection_primary_key), - full_keys(@reflection.through_reflection.table_name, source_primary_key)), - polymorphic_join + @owner.class.quote_value(@reflection.through_reflection.klass.name) ] + end + end + + "INNER JOIN %s ON %s %s #{@reflection.options[:joins]} #{custom_joins}" % [ + @reflection.through_reflection.table_name, + composite_join_clause( + full_keys(@reflection.table_name, reflection_primary_key), + full_keys(@reflection.through_reflection.table_name, source_primary_key)), + polymorphic_join + ] end - + def construct_sql case when @reflection.options[:finder_sql]