Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

has_many :through associations give different results depending on eager-loading via :include

#2451

class User
  has_many :comments
  has_many :posts, :through => :comments
end

class Comment
  belongs_to :user
  belongs_to :post
end

x = User.create
x.comments.create :post_id => nil

x.posts #=> []

x = User.find :first

x.posts #=> []

x = User.find :first, :include => [:posts]
x.posts #=> [nil] !!!

I'm not sure if posts should return [] or [nil], but the result should be consistent regardless of whether the association was eager-loaded or not.

Reported by David Lee · April 7th, 2009 @ 11:40 PM

State: stale
Milestone: 3.x
Assigned to: Aaron Patterson Aaron Patterson
Importance: none

Activity

  1. Tatsuya Ono
  2. Tatsuya Ono
    Tatsuya Ono

    I wrote a patch for this issue against 2-3-stable.

    I also put a simple project on github which allows you to reproduce this issue easily.
    http://github.com/ono/eager_load_issue/tree/master

    Clone it then run rake test. It will be failed despite for it should be passed.

        # sets up data
        
        u1 = User.find :all
        u2 = User.find :all, :include=>['posts_commented']
        assert_equal u1[0].posts_commented.size, u2[0].posts_commented.size
    

    You will succeed to pass the test if you apply the patch attached.

    June 16th, 2009 @ 01:40 AM

  3. Jeremy Kemper
    Jeremy Kemper
    • Milestone changed from 2.x to 3.x

    May 4th, 2010 @ 06:48 PM

  4. Jon Leighton
    Jon Leighton
    • Assigned user set to Aaron Patterson
    • Importance changed from to

    Can this ticket be closed or at least marked as stale please? If you look at association_preload.rb in current master, you will see that it does Array.wrap(associated_record), which deals with the case of associated_record being nil, which is the source of the problem reported.

    December 16th, 2010 @ 12:35 AM

  5. Aaron Patterson
    Aaron Patterson
    • State changed from new to stale

    @Jon yes. Marking as stale. :-)

    December 16th, 2010 @ 01:46 AM