Skip to content

Commit

Permalink
Raise when a through association has an ambiguous reflection name
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelfranca committed Dec 29, 2016
1 parent 249f71a commit 0944182
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 10 deletions.
4 changes: 4 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* Raises when a through association has an ambiguous reflection name.

*Rafael Mendonça França*

* Raises when `ActiveRecord::Migration` is inherited directly.

*Rafael Mendonça França*
Expand Down
15 changes: 15 additions & 0 deletions activerecord/lib/active_record/associations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,21 @@ def initialize(owner = nil, reflection = nil)
end
end

class AmbiguousSourceReflectionForThroughAssociation < ActiveRecordError # :nodoc:
def initialize(klass, macro, association_name, options, possible_sources)
example_options = options.dup
example_options[:source] = possible_sources.first

super("Ambiguous source reflection for through association. Please " \
"specify a :source directive on your declaration like:\n" \
"\n" \
" class #{klass} < ActiveRecord::Base\n" \
" #{macro} :#{association_name}, #{example_options}\n" \
" end"
)
end
end

class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc:
end

Expand Down
16 changes: 7 additions & 9 deletions activerecord/lib/active_record/reflection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -878,15 +878,13 @@ def source_reflection_name # :nodoc:
}

if names.length > 1
example_options = options.dup
example_options[:source] = source_reflection_names.first
ActiveSupport::Deprecation.warn \
"Ambiguous source reflection for through association. Please " \
"specify a :source directive on your declaration like:\n" \
"\n" \
" class #{active_record.name} < ActiveRecord::Base\n" \
" #{macro} :#{name}, #{example_options}\n" \
" end"
raise AmbiguousSourceReflectionForThroughAssociation.new(
active_record.name,
macro,
name,
options,
source_reflection_names
)
end

@source_reflection_name = names.first
Expand Down
2 changes: 1 addition & 1 deletion activerecord/test/cases/errors_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ def test_can_be_instantiated_with_no_args
base = ActiveRecord::ActiveRecordError
error_klasses = ObjectSpace.each_object(Class).select { |klass| klass < base }

error_klasses.each do |error_klass|
(error_klasses - [ActiveRecord::AmbiguousSourceReflectionForThroughAssociation]).each do |error_klass|
begin
error_klass.new.inspect
rescue ArgumentError
Expand Down

0 comments on commit 0944182

Please sign in to comment.