Reputation: 3250
I have a CourseSession
model. Each CourseSession
has some lessons
.
I would like to call: lesson.course_session
and get the CourseSession
that refers to the lesson
.
I don't want to use a foreign key in order to practice 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.
So how do I define the associations in order to achieve lesson.course_session
?
Upvotes: 0
Views: 86
Reputation: 3407
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:
belongs_to :course_session, primary_key: :effective_date, foreign_key: :effective_date
And in 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
Upvotes: 1