我有一个CourseSession
模型。每个CourseSession
都有一些lessons
。
我想打个电话:lesson.course_session
,并得到引用CourseSession
的{{1}}。
我不想使用外键来练习滑轨。
如何在它们之间建立联系?每个lesson
都有一个唯一的Lesson
列,其对应于effective_date
模型中的effective_date
。
那么,如何定义关联才能实现CourseSession
?
答案 0 :(得分:1)
我认为这是可能的,但不是建议的方法。如果是为了学习新知识,请继续。但是无论如何,在Lesson模型中,请使用:
belongs_to :course_session, primary_key: :effective_date, foreign_key: :effective_date
在CourseSession中:
has_many :lessons, primary_key: :effective_date, foreign_key: :effective_date
在这里找到了一个谈论这个的帖子:Belongs_to primary key?
在Options /:primary_key下查看https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to