Skip to content

Commit

Permalink
Ensure self referential HABTM associations raise an exception if asso…
Browse files Browse the repository at this point in the history
…ciation_foreign_key is missing. [#1252 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information
tomlea authored and lifo committed Mar 6, 2009
1 parent 8bc0f90 commit c896d56
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
10 changes: 10 additions & 0 deletions activerecord/lib/active_record/associations.rb
Expand Up @@ -51,6 +51,12 @@ def initialize(owner, reflection)
end
end

class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc:
def initialize(reflection)
super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.")
end
end

class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
def initialize(reflection)
super("Can not eagerly load the polymorphic association #{reflection.name.inspect}")
Expand Down Expand Up @@ -1526,6 +1532,10 @@ def create_has_and_belongs_to_many_reflection(association_id, options, &extensio
options[:extend] = create_extension_modules(association_id, extension, options[:extend])

reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self)

if reflection.association_foreign_key == reflection.primary_key_name
raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
end

reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))

Expand Down
Expand Up @@ -740,6 +740,14 @@ def test_symbols_as_keys
assert_equal developer, project.developers.find(:first)
assert_equal project, developer.projects.find(:first)
end

def test_self_referential_habtm_without_foreign_key_set_should_raise_exception
assert_raise(ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded) {
Member.class_eval do
has_and_belongs_to_many :friends, :class_name => "Member", :join_table => "member_friends"
end
}
end

def test_dynamic_find_should_respect_association_include
# SQL error in sort clause if :include is not included
Expand Down

0 comments on commit c896d56

Please sign in to comment.