Includes HABTM returns correct size now. It's caused by the join dependency

only instantiates one HABTM object because the join table hasn't a primary key.
Updated commit from @bigxiang commit dbaa837

Fixes #16032.

Examples:

    before:

    Project.first.salaried_developers.size # => 3
    Project.includes(:salaried_developers).first.salaried_developers.size # => 1

    after:

    Project.first.salaried_developers.size # => 3
    Project.includes(:salaried_developers).first.salaried_developers.size # => 3
This commit is contained in:
Sergio Cambra 2014-11-21 15:54:01 -10:00
parent f9e0ec5449
commit 33a5416461
3 changed files with 41 additions and 2 deletions

@ -1,3 +1,22 @@
* Includes HABTM returns correct size now. It's caused by the join dependency
only instantiates one HABTM object because the join table hasn't a primary key.
Fixes #16032.
Examples:
before:
Project.first.salaried_developers.size # => 3
Project.includes(:salaried_developers).first.salaried_developers.size # => 1
after:
Project.first.salaried_developers.size # => 3
Project.includes(:salaried_developers).first.salaried_developers.size # => 3
*Bigxiang*
* Fix accessing of fixtures having non-string labels like Fixnum.
*Prathamesh Sonpatki*

@ -150,7 +150,8 @@ def instantiate(result_set, aliases)
message_bus.instrument('instantiation.active_record', payload) do
result_set.each { |row_hash|
parent = parents[row_hash[primary_key]] ||= join_root.instantiate(row_hash, column_aliases)
parent_key = primary_key ? row_hash[primary_key] : row_hash
parent = parents[parent_key] ||= join_root.instantiate(row_hash, column_aliases)
construct(parent, join_root, row_hash, result_set, seen, model_cache, aliases)
}
end
@ -232,7 +233,7 @@ def build(associations, base_klass)
end
def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
primary_id = ar_parent.id
primary_id = ar_parent.id || row
parent.children.each do |node|
if node.reflection.collection?

@ -902,4 +902,23 @@ def test_with_symbol_class_name
DeveloperWithSymbolClassName.new
end
end
def test_preloaded_associations_size
assert_equal Project.first.salaried_developers.size,
Project.preload(:salaried_developers).first.salaried_developers.size
assert_equal Project.includes(:salaried_developers).references(:salaried_developers).first.salaried_developers.size,
Project.preload(:salaried_developers).first.salaried_developers.size
# Nested HATBM
first_project = Developer.first.projects.first
preloaded_first_project =
Developer.preload(projects: :salaried_developers).
first.
projects.
detect { |p| p.id == first_project.id }
assert preloaded_first_project.salaried_developers.loaded?, true
assert_equal first_project.salaried_developers.size, preloaded_first_project.salaried_developers.size
end
end