This project is archived and is in readonly mode.

#306 ✓duplicate
Mark Roghelia

Eager fetching a HABTM fails when the HABTM uses the "include" option

Reported by Mark Roghelia | June 2nd, 2008 @ 10:53 PM

This ticket assumes that the fix for eager fetching HABTMs that is detailed in ticket #304 has been applied.

Eager fetching a "has_and_belongs_to_many" association as part of a find generates as error when that association is defined to include another HABTM with the "include" option.

Consider the following example. A UserProfile class has a "has_and_belongs_to_many" association with UserRole. UserRole in turn has a HABTM with Permission. In UserProfile, the "user_roles" association is defined to include the permissions, as follows:

class UserProfile < ActiveRecord::Base

has_and_belongs_to_many :user_roles, :include => :permissions


If I call UserProfile.find(1, :include => :user_roles), I get the following error:

/Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/commands/runner.rb:47: /Users/mark/src/msd/lib/preload_association.rb:45:in `add_preloaded_records_to_collection': You have a nil object when you didn't expect it! (NoMethodError)

You might have expected an instance of Array.

The error occurred while evaluating nil.each from /Users/mark/src/msd/lib/preload_association.rb:63:in `set_association_collection_records'

from /Users/mark/src/msd/lib/preload_association.rb:61:in `each'

from /Users/mark/src/msd/lib/preload_association.rb:61:in `set_association_collection_records'

from /Users/mark/src/msd/lib/preload_association.rb:109:in `preload_has_and_belongs_to_many_association'

from /Users/mark/src/msd/lib/preload_association.rb:40:in `send'

from /Users/mark/src/msd/lib/preload_association.rb:40:in `preload_one_association'

from /Users/mark/src/msd/lib/preload_association.rb:38:in `each'

from /Users/mark/src/msd/lib/preload_association.rb:38:in `preload_one_association'

... 11 levels...

from /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/commands/runner.rb:47

from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'

from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:27:in `require'

from ./script/runner:3

This seems to result from the "_parent_id" column not being included in the query. If I leave ":include => :permission" out of the definition of "user_roles", this works (assuming the patch from ticket #304 has been applied).

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 »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

Referenced by