在单个继承表和另一个表中的类之间建立了许多关联
我在部门和研究人员之间的许多关系中都有一个名为“关系”的联合表。
我希望能够通过做 decression.find(1).pudents
获得学生列表,但是我会得到 activerecord :: HasmanyThroughSourCeasSociationNotFoundError(找不到源协会: 。
模型研究员
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来源:
选项期望关联作为参数。在内部,rails在修复 has_many之前:学生关联,要注意的几件事:
要解决关联,我们可以使用
scope> scope
has_many
的参数/code>方法:
现在,我们需要修复
关系之间的关联
和研究人员
:您还可以让Rails通过在
关系>中定义其他关联来完成工作< /code>,无需范围:
https://api.rubyonrails.orgs.org/classes/classecoping/scoping/nemed/nemed/nemed/classml-classml-classml-w.metml#method-unpmetml#method-i-scope
https://api.rubyonrails.orgs.org/classes/classes/activerecord/activerecord/reflecord/reflection/reflection/classmethod/classmethods.htmlluctions.html#method-method-i-reflect_sass_sass_sassociation
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
scope
argument ofhas_many
method:Now, we need to fix the association between
Relation
andResearcher
: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