1
votes

I have to create relationship between student, courses and enrolment.

One student can enrol in only one course. A course can be enrolled by many students.

How to acheive this ?

I was able to create has_many_through relationship like this

class
  Student < User
    has_many :enrollments
    has_many :course , through: :enrollments
end

class Course < ActiveRecord::Base
    has_many :enrollments
    has_many :students, through: :enrollments, class_name: "User"
end

class Enrollment < ActiveRecord::Base
    belongs_to :student, class_name: "User"
    belongs_to :course
end

But this works only for has_many on both the sides of students and courses. But I want only one student to enrol in one course like this

class Student < User
    has_one :enrollment
    has_one :course , through: :enrollment
end

But this does not work. When I do this

Student.first.enrollment.create(course: Course.last)

I get an error like this

NoMethodError: undefined method `enrollment' for #<Student:0x007f7ff8baf4a8>
1
I assume you try to do it in the console. Did you restart your console (or type reload!) after you changed the file? - Marek Lipka
Thanks. I tried reload! but did not work. - PRN
But this worked. Have to use enrolments (plural) Student.first.enrollments.create(course: Course.last) - PRN
Again: Is the error message the same? Or is it undefined method create on nil? - Marek Lipka
But still student is able to enrol in many courses. How to restrict a student to enrol in only one course - PRN

1 Answers

0
votes

Thanks to Marek Lipka for suggesting this solution.

Add validation in Enrollment

class Enrollment < ActiveRecord::Base
    belongs_to :student, class_name: "User"
    belongs_to :course

    validates :student , uniqueness: true
end

And use has_many enrollments

class Student < User
    has_many :enrollments
    has_many :course , through: :enrollments
end