From 987d06ab0fb788dc38095b9a0eab7c632d8e8251 Mon Sep 17 00:00:00 2001 From: Greg Date: Thu, 21 Jan 2010 00:10:26 -0500 Subject: [PATCH] Illustrate order of nulls by MySQL --- activerecord/test/cases/associations/eager_test.rb | 29 ++++++++++++++++++++ 1 files changed, 29 insertions(+), 0 deletions(-) diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index d23f86b..ada0a34 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -223,6 +223,35 @@ class EagerAssociationTest < ActiveRecord::TestCase end end + def test_eager_association_loading_with_belongs_to_and_order_by_foreign_key + # Note: Posts 3 and 6 have no Comments. There is no Comment 4. + + # No surprises here: + posts = Post.find(:all, :include => :comments, :order => 'posts.id, comments.post_id') + assert_equal [1,2,3,4,5,6,7], posts.collect { |p| p.id } + comments = posts.collect { |p| p.comments }.flatten + assert_equal [1,2,3,5,6,7,8,9,10,11], comments.collect { |c| c.id } + + # Posts without Comments are ordered first by MySQL because for them, comments.post_id is null and MySQL orders null values first: + posts = Post.find(:all, :include => :comments, :order => 'comments.post_id') + assert_equal [3,6,1,2,4,5,7], posts.collect { |p| p.id } + + # This fails in MySQL because Posts without Comments are ordered first: + posts = Post.find(:all, :include => :comments, :limit => 5, :order => 'comments.post_id') + assert_equal [1,2,4,5,7], posts.collect { |p| p.id } + # MySQL: [3,6,1,2,4] + + # Ugly MySQL fix: + + # Posts without Comments are ordered last by MySQL: + # posts = Post.find(:all, :include => :comments, :order => 'ISNULL(comments.post_id), comments.post_id') + # assert_equal [1,2,4,5,7,3,6], posts.collect { |p| p.id } + + # Posts without Comments are ordered last by MySQL: + # posts = Post.find(:all, :include => :comments, :limit => 5, :order => 'ISNULL(comments.post_id), comments.post_id') + # assert_equal [1,2,4,5,7], posts.collect { |p| p.id } + end + def test_eager_association_loading_with_belongs_to_and_conditions_hash comments = [] assert_nothing_raised do -- 1.6.3.3