Skip to content

Commit

Permalink
Merge pull request #12362 from arthurnn/inverse_on_find
Browse files Browse the repository at this point in the history
fix .find when inverse is loaded
Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/associations/collection_association.rb
	activerecord/test/cases/associations/has_many_associations_test.rb
  • Loading branch information
rafaelfranca committed Sep 25, 2013
1 parent 8fbc416 commit 9c18c8c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
6 changes: 6 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,5 +1,11 @@
## unreleased ##

* Fixed `ActiveRecord::Associations::CollectionAssociation#find`
when using `has_many` association with `:inverse_of` and finding an array of one element,
it should return an array of one element too.

*arthurnn*

* Callbacks on has_many should access the in memory parent if a inverse_of is set.

*arthurnn*
Expand Down
Expand Up @@ -82,14 +82,14 @@ def find(*args)
if options[:finder_sql]
find_by_scan(*args)
elsif options[:inverse_of] && loaded?
args = args.flatten
raise RecordNotFound, "Couldn't find #{scope.klass.name} without an ID" if args.blank?
args_flatten = args.flatten
raise RecordNotFound, "Couldn't find #{scope.klass.name} without an ID" if args_flatten.blank?

result = find_by_scan(*args)

result_size = Array(result).size
if !result || result_size != args.size
scope.raise_record_not_found_exception!(args, result_size, args.size)
if !result || result_size != args_flatten.size
scope.raise_record_not_found_exception!(args_flatten, result_size, args_flatten.size)
else
result
end
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/associations/has_many_associations_test.rb
Expand Up @@ -421,6 +421,18 @@ def test_find_string_ids_when_using_finder_sql
assert client_ary.include?(client)
end

def test_find_ids_and_inverse_of
force_signal37_to_load_all_clients_of_firm

firm = companies(:first_firm)
client = firm.clients_of_firm.find(3)
assert_kind_of Client, client

client_ary = firm.clients_of_firm.find([3])
assert_kind_of Array, client_ary
assert_equal client, client_ary.first
end

def test_find_all
firm = Firm.all.merge!(:order => "id").first
assert_equal 2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
Expand Down

0 comments on commit 9c18c8c

Please sign in to comment.