module ActiveRecord
module Associations
class HasManyThroughAssociation < AssociationProxy

def construct_owner_attributes_with_bugfix(reflection)
if reflection.macro == :belongs_to
{ reflection.klass.primary_key => \
@owner[reflection.primary_key_name] }
else
construct_quoted_owner_attributes_without_bugfix(reflection)
end
end
alias_method_chain :construct_owner_attributes, :bugfix

def construct_quoted_owner_attributes_with_bugfix(reflection)
if reflection.macro == :belongs_to
{ reflection.klass.primary_key => \
@owner.send(:attributes_with_quotes)[reflection.primary_key_name] }
else
construct_quoted_owner_attributes_without_bugfix(reflection)
end
end
alias_method_chain :construct_quoted_owner_attributes, :bugfix

end

module ClassMethods
class JoinDependency
class JoinAssociation < JoinBase

def association_join_with_bugfix
res = association_join_without_bugfix

return res unless reflection.macro == :has_many and \
reflection.options[:through] and \
reflection.through_reflection.macro == :belongs_to

connection = reflection.active_record.connection

if through_reflection.options[:as]
jt_foreign_key = through_reflection.options[:as].to_s + '_id'
else
jt_foreign_key = through_reflection.primary_key_name
end

erroneous_string = " ON (%s.%s = %s.%s" % [
connection.quote_table_name(parent.aliased_table_name),
connection.quote_column_name(parent.primary_key),
connection.quote_table_name(aliased_join_table_name),
connection.quote_column_name(jt_foreign_key)
]

if (index = res.index(erroneous_string))
correct_string = " ON (%s.%s = %s.%s" % [
connection.quote_table_name(parent.aliased_table_name),
connection.quote_column_name(jt_foreign_key),
connection.quote_table_name(aliased_join_table_name),
connection.quote_column_name(
through_reflection.klass.primary_key
)
]
res[index, erroneous_string.length] = correct_string
end

res
end
alias_method_chain :association_join, :bugfix

end
end
end

end
end