aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activerecord/CHANGELOG.md7
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb6
-rw-r--r--activerecord/test/cases/associations/eager_test.rb13
3 files changed, 25 insertions, 1 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 87420a0746..a9fba7da72 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,10 @@
+* Pass SQL group by values when including scoped association
+
+ Fixes problem when added `group()` in association scope was lost
+ in eager loaded association.
+
+ *Lucjan Suski*
+
* Version the API presented to migration classes, so we can change parameter
defaults without breaking existing migrations, or forcing them to be
rewritten through a deprecation cycle.
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
index e11a5cfb8a..91e7f90739 100644
--- a/activerecord/lib/active_record/associations/preloader/association.rb
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -107,7 +107,7 @@ module ActiveRecord
@preloaded_records = slices.flat_map do |slice|
records_for(slice)
end
- @preloaded_records.group_by do |record|
+ @preloaded_records.group_by do |record|
convert_key(record[association_key_name])
end
end
@@ -139,6 +139,10 @@ module ActiveRecord
scope.order!(order_values)
end
+ if group_values = preload_values[:group] || values[:group]
+ scope.group!(group_values)
+ end
+
if preload_values[:reordering] || values[:reordering]
scope.reordering_value = true
end
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 0c09713971..622c984b3b 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -1242,6 +1242,19 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_equal projects.last.mentor.developers.first.contracts, projects.last.developers.last.contracts
end
+ def test_eager_load_with_group_clause
+ assert_nothing_raised(ActiveRecord::StatementInvalid) do
+ subclass = Class.new(ActiveRecord::Base) do
+ def self.name; "Author"; end
+ self.table_name = "authors"
+ has_many :posts_ordered_by_comments_tags_count, -> { joins('LEFT JOIN comments ON comments.post_id = posts.id').order("SUM(comments.tags_count)").group('posts.id') }, :class_name => "Post"
+ end
+
+ posts = subclass.includes(:posts_ordered_by_comments_tags_count).first.posts_ordered_by_comments_tags_count
+ assert_equal subclass.first.posts_ordered_by_comments_tags_count, posts
+ end
+ end
+
test "scoping with a circular preload" do
assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) }
end