I'm having some trouble defining a has_many :through relationship in Rails 5 where the join and target models both reside within a namespace. I have a Student model that I want to join to Admission::Application through Admission::ApplicationStudent. When I attempt to access the admission_applications association I get a NameError: "uninitialized constant Student::Application".
Here are my model definitions:
student.rb
class Student < ApplicationRecord
  has_many :admission_application_students,
    class_name: 'Admission::ApplicationStudent',
    inverse_of: :student
  has_many :admission_applications,
    through: :admission_application_students,
    source: :application
end
admission/application_student.rb
class Admission::ApplicationStudent < ApplicationRecord
  belongs_to :application
  belongs_to :student,
    class_name: 'Student',
    inverse_of: :admission_application_students
end
admission/application.rb
class Admission::Application < ApplicationRecord
  has_many :application_students
  has_many :students,
    through: :application_students,
    source: :student
end
Incidentally, I generated all three models with standard commands:
rails g model student
rails g model 'Admission::Application'
rails g model 'Admission::ApplicationStudent'
The application_students and students associations are both functioning correctly from Application. I can also retrieve a collection of ApplicationStudent records from the admission_application_students association on Student. If Student knows how to make it that far, it seems like :source has to be the problem, but I've been researching and testing since yesterday, and I no longer feel like I'm making progress. Any help would be appreciated.
You need to specify the class_name for admission_applications association since it is also in a different namespace:
class Student < ApplicationRecord
  has_many :admission_application_students, class_name: 'Admission::ApplicationStudent'
  has_many :admission_applications, 
                 through: :admission_application_students, 
                  source: :application, 
              class_name: 'Admission::Application'
end
For more information see the documentation for has_many and Section 3.4 Controlling Association Scope of the Active Record Associations Guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With