Created
November 12, 2010 15:39
-
-
Save pdswan/674231 to your computer and use it in GitHub Desktop.
swaps the foreign key and primary key to fix has_many and has_one through belongs_to in Rails 2.3.x
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
class ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation | |
# has_many and has_one through belongs_to are broken becuase the order of the primary key | |
# and foreign table key need to be reversed. this detects and fixes it. | |
def association_join_with_through_belongs_to_fix | |
join = association_join_without_through_belongs_to_fix | |
if [:has_many, :has_one].include?(reflection.macro) && reflection.options[:through] && source_reflection.macro == :belongs_to | |
connection = reflection.active_record.connection | |
parent_table_name = connection.quote_table_name(parent.aliased_table_name) | |
parent_key = connection.quote_column_name(parent.primary_key) | |
join_table_name = connection.quote_table_name(aliased_join_table_name) | |
jt_foreign_key = through_reflection.options[:as] ? through_reflection.options[:as].to_s + '_id' : through_reflection.primary_key_name | |
join_key = connection.quote_column_name(jt_foreign_key) | |
# if this is a belongs to we need to swap the order in which the keys are used | |
join = join.gsub(/(#{parent_table_name}\.)#{parent_key}/, "\\1#{join_key}").gsub(/(#{join_table_name}\.)#{join_key}/, "\\1#{parent_key}") | |
end | |
join | |
end | |
alias_method_chain :association_join, :through_belongs_to_fix | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment