Pass SQL group by values when including scoped association

Fixes problem when added `group()` in association scope was lost
in eager loaded association.
This commit is contained in:
Lucjan Suski 2015-12-15 14:32:34 +01:00
parent e73fe1dd8c
commit 9d21a7fc50
3 changed files with 25 additions and 1 deletions

@ -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 * Version the API presented to migration classes, so we can change parameter
defaults without breaking existing migrations, or forcing them to be defaults without breaking existing migrations, or forcing them to be
rewritten through a deprecation cycle. rewritten through a deprecation cycle.

@ -107,7 +107,7 @@ def load_records
@preloaded_records = slices.flat_map do |slice| @preloaded_records = slices.flat_map do |slice|
records_for(slice) records_for(slice)
end end
@preloaded_records.group_by do |record| @preloaded_records.group_by do |record|
convert_key(record[association_key_name]) convert_key(record[association_key_name])
end end
end end
@ -139,6 +139,10 @@ def build_scope
scope.order!(order_values) scope.order!(order_values)
end end
if group_values = preload_values[:group] || values[:group]
scope.group!(group_values)
end
if preload_values[:reordering] || values[:reordering] if preload_values[:reordering] || values[:reordering]
scope.reordering_value = true scope.reordering_value = true
end end

@ -1242,6 +1242,19 @@ def test_eager_load_multiple_associations_with_references
assert_equal projects.last.mentor.developers.first.contracts, projects.last.developers.last.contracts assert_equal projects.last.mentor.developers.first.contracts, projects.last.developers.last.contracts
end 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 test "scoping with a circular preload" do
assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) } assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) }
end end