Reputation: 649
I have two rails models associated with each other: students and courses. Multiple students can take multiple courses, so I decided to use a has_many_through association... as you can see below.
I also added an index to make sure a student does not enroll for a course twice. However, whe I try to enroll it doesn't go through.
student_enrollments:
belongs_to :students
belongs_to :courses
validates :matriculation_number, presence: :true
validates :course_code, presence: :true
student_enrollment schema
create_table "student_enrollments", id: false, force: :cascade do |t|
t.string "course_code", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "matriculation_number"
t.index ["course_code"], name: "index_student_enrollments_on_student_id_and_course_code", unique: true
end
student_enrollments_controller:
class StudentEnrollmentsController < ApplicationController
before_action :authenticate_student!
def new
@courses = Course.all
@course = []
i = 0
while i < @courses.length
@course.push(@courses[i].course_code)
i += 1
end
@enrollment = StudentEnrollment.new
end
def create
@enrollment = StudentEnrollment.new(enrollment_params)
if @enrollment.save
flash[:success] = "enrollment successful."
redirect_to new_student_enrollment_path
else
flash[:danger] = "Enrollment failed."
redirect_to new_student_enrollment_path
end
end
private
def enrollment_params
params.require(:student_enrollment).permit(:course_code, :matriculation_number)
end
end
student
has_many :student_enrollments
has_many :courses, through: :student_enrollments
course
has_many :student_enrollments
has_many :students, through: :student_enrollments
I also added an index to make sure a student does not enroll for a course twice. However, whe I try to enroll it doesn't go through. The output when I try to create the entry via the console: ActiveRecord::RecordInvalid (Validation failed: Students must exist, Courses must exist)
.
Upvotes: 0
Views: 35
Reputation: 269
As of Rails 5, belongs_to
associations are required, unless passing in the optional: true
flag.
You can either update your associations so you can create a StudentEnrollment without a Student or Course passed in, or you can pass in student_id
and course_id
attributes when creating the new object.
To disable those validations you can just do:
belongs_to :student, optional: true
belongs_to :course, optional: true
Upvotes: 1