我在SO question中提出了完全相同的问题。
我的答案实现如下:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
##### The next two lines are the important part ######
has_many :notes, class_name: LessonNotes::Engine::Note, foreign_key: "teacher_id"
has_many :notes, class_name: LessonNotes::Engine::Note, foreign_key: "student_id"
has_many :students, class_name: "User",
foreign_key: "teacher_id"
belongs_to :teacher, class_name: "User"
end
但是,我收到此错误:uninitialized constant LessonNotes::Engine::Note
如果我删除引擎上的has_many
个关联之一并离开另一个,那么一切正常......但
更新
通过更改相关的两行来消除uninitialized constant
错误:
has_many :notes, class_name: "::LessonNotes::Engine::Note", foreign_key: "student_id"
has_many :notes, class_name: "::LessonNotes::Engine::Note", foreign_key: "teacher_id"
但是现在似乎第二个协会会覆盖第一个协会。 ActiveRecord只查找第二个外键 - 在本例中为“teacher_id” - 并忽略第一个外键。这是预期的行为吗?
答案 0 :(得分:1)
是的,这是预期的行为。您正在定义相同的关联(按名称:注释)两次,因此第二个声明将覆盖第一个。
您必须重命名关联。
has_many :student_notes, class_name: "::LessonNotes::Engine::Note", foreign_key: "student_id"
has_many :teacher_notes, class_name: "::LessonNotes::Engine::Note", foreign_key: "teacher_id"
如果你想同时访问这两个,你可以定义类似这样的东西
def notes
student_notes + teacher_notes
end