This project is archived and is in readonly mode.

#5623 new
eirc

Eager loading a nested association with conditions or order eager loads the wrong associated records

Reported by eirc | September 13th, 2010 @ 01:41 PM

Eager loading a nested has_many association with conditions or order on the nested table loads only the first record.

class AuthorAddress < ActiveRecord::Base
  has_one :author
end

class Author < ActiveRecord::Base
  has_many :posts
  belongs_to :author_address
end

class Post < ActiveRecord::Base
  belongs_to :author
end
author_address = AuthorAddress.find(1, :include => {:author => :posts}, :order => "authors.id")

Using an order or conditions clause on a different table than the base one uses legacy SQL (LEFT OUTER JOIN) to load, but it incorrectly (eagerly) loads posts. Only one, of the many posts, is eagerly loaded and unfortunately the association thinks it is fully loaded.

Therefore doing something like this:

author_address.author.posts.length

returns a different answer than this:

author_address.author.posts.count

(which of course hits the database again to get the correct answer)

Any ideas on where we can look to solve this?

The above code works correctly in Rails 1.2.6!

Attached you'll find failing tests.

Thanks in advance for any help.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Tickets have moved to Github

The new ticket tracker is available at https://github.com/rails/rails/issues

Shared Ticket Bins

Referenced by

Pages