I have a join table named Relations in a many to many relationship between departments and researchers.
I want to be able to get a list of students by doing Department.find(1).students but I am getting ActiveRecord::HasManyThroughSourceAssociationNotFoundError (Could not find the source association(s) :students in model Researcher. Try 'has_many :students, :through => :researchers, :source => <name>'.)
Why isn't it using the scope from the table Researcher?
class Department < ApplicationRecord
has_many :relations
has_many :researchers, through: :relations
has_many :students, source: :students, through: :researchers
has_many :advisors, source: :advisors, through: :researchers
end
class Relation < ApplicationRecord
belongs_to :researcher
belongs_to :department
end
class Reseacher < ApplicationRecord
scope :students, -> { where(type: 'Student') }
scope :advisors, -> { where(type: 'Advisor') }
end
class Student < Researcher
has_many :relations, foreign_key: :department_id
has_many :departments, through: :relations
end
class Advisor < Researcher
has_many :relations, foreign_key: :department_id
has_many :departments, through: :relations
end
source:option expects an association as argument. Internally, rails runs a reflection on the argument, like:Before fixing has_many :students association, a few things to note:
To fix the association we can use
scopeargument ofhas_manymethod:Now, we need to fix the association between
RelationandResearcher:You can also let rails do the work by defining additional associations in
Relation, no scope required:https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
https://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-scope
https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
https://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-reflect_on_association