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 across namespace fails

#6094
class Person < ActiveRecord::Base
  has_many :manager_roles, :class_name => "Organization::Department"
  has_many :departments, :through => :manager_roles
end

module Organization
  class Department < ActiveRecord::Base
    has_many :manager_roles
  end
  
  class ManagerRole < ActiveRecord::Base
    belongs_to :department
    belongs_to :person
  end
end

has_many :departments, :through => :manager_roles will crash:

NameError: uninitialized constant Person::Department
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/base.rb:1199:in `compute_type'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/reflection.rb:162:in `send'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/reflection.rb:162:in `klass'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/through_association_scope.rb:56:in `construct_joins'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/through_association_scope.rb:11:in `construct_scope'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/has_many_through_association.rb:84:in `find_target'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/association_collection.rb:409:in `load_target'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/association_proxy.rb:145:in `inspect'

We can work around it by changing ManagerRole to specifically declare the class name:

  class ManagerRole < ActiveRecord::Base

belongs_to :department, :class_name =&gt; &quot;Organization::Department&quot;
belongs_to :person



end

It appears that compute_type would need to also search the module of the join model.

Reported by JackC · November 30th, 2010 @ 10:03 PM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. JackC
    JackC
    • Tag changed from activerecord, has_many_through, module, namespace to activerecord, documentation, has_many_through, module, namespace

    On further investigation, setting :class_name on the has_many :through relationship actually works.

    The problem is actually in the documentation. The docs say that :class_name is ignored with has_many :through, but it actually works.

    November 30th, 2010 @ 10:17 PM

  2. Dan Pickett
    Dan Pickett

    JackC, perhaps you could supply a test and a documentation patch that verifies and clarifies this behavior?

    March 12th, 2011 @ 04:24 PM