This project is archived and is in readonly mode.

#6094 new

has_many :through across namespace fails

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

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

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

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


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

Comments and changes to this ticket

  • JackC

    JackC November 30th, 2010 @ 10:17 PM

    • 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.

  • Dan Pickett

    Dan Pickett March 12th, 2011 @ 04:24 PM

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

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>

People watching this ticket