Skip to content

Commit

Permalink
Load the first and not the last has_one result when doing join-based …
Browse files Browse the repository at this point in the history
…eager loading

This matters when the has_one is defined with an order in which case
there is an expectation that the first one will be loaded.

[#904 state:resolved]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information
tarmo authored and jeremy committed Aug 26, 2008
1 parent bff0f5f commit 6ae0a05
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions activerecord/lib/active_record/associations.rb
Expand Up @@ -1734,6 +1734,7 @@ def construct_association(record, join, row)
collection.target.push(association)
when :has_one
return if record.id.to_s != join.parent.record_id(row).to_s
return if record.instance_variable_defined?("@#{join.reflection.name}")
association = join.instantiate(row) unless row[join.aliased_primary_key].nil?
record.send("set_#{join.reflection.name}_target", association)
when :belongs_to
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/associations/eager_test.rb
Expand Up @@ -38,6 +38,12 @@ def test_loading_with_one_association
assert_equal Post.find(1).last_comment, post.last_comment
end

def test_loading_with_one_association_with_non_preload
posts = Post.find(:all, :include => :last_comment, :order => 'comments.id DESC')
post = posts.find { |p| p.id == 1 }
assert_equal Post.find(1).last_comment, post.last_comment
end

def test_loading_conditions_with_or
posts = authors(:david).posts.find(:all, :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'")
assert_nil posts.detect { |p| p.author_id != authors(:david).id },
Expand Down
Expand Up @@ -91,4 +91,14 @@ def test_has_one_through_nonpreload_eager_loading_through_polymorphic
assert_not_nil assert_no_queries {members[0].sponsor_club}
end

def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record
Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save!
members = assert_queries(1) do
Member.find(:all, :include => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC') #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries { members[0].sponsor_club }
assert_equal clubs(:crazy_club), members[0].sponsor_club
end

end

0 comments on commit 6ae0a05

Please sign in to comment.