[英]Define relationship between 2 models
I have a CourseSession
model. 我有一个
CourseSession
模型。 Each CourseSession
has some lessons
. 每个
CourseSession
都有一些lessons
。
I would like to call: lesson.course_session
and get the CourseSession
that refers to the lesson
. 我想打电话:
lesson.course_session
并获得CourseSession
引用的lesson
。
I don't want to use a foreign key in order to practice rails. 我不想使用外键来练习Rails。
How can I connect between them? 如何在它们之间建立联系? Every
Lesson
has a unique effective_date
column that coresponds to an effective_date
in the CourseSession
model. 每个
Lesson
都有一个唯一的effective_date
列,该列对应于CourseSession
模型中的effective_date
日期。
So how do I define the associations in order to achieve lesson.course_session
? 那么,如何定义关联以实现
lesson.course_session
?
It is possible, I guess, but not an advised approach. 我想这是可能的,但不是建议的方法。 If it's for the sake of learning something new, go ahead.
如果是为了学习新知识,请继续。 But anyway, in the Lesson model, use:
但是无论如何,在Lesson模型中,请使用:
belongs_to :course_session, primary_key: :effective_date, foreign_key: :effective_date
And in CourseSession: 在CourseSession中:
has_many :lessons, primary_key: :effective_date, foreign_key: :effective_date
Found a post here talking about this: Belongs_to primary key? 在这里找到了一个谈论这个的帖子: 属于主键?
Take a look at https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to under Options/:primary_key 在Options /:primary_key下查看https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.