ActiveRecord::InvalidForeignKey does not raise

Asked 2 years ago, Updated 2 years ago, 90 views

  • students
  • subjects
  • students_subjects (intermediate table)
    • student_id
    • subject_id
  • student_id
  • subject_id

The students_subjects have foreign key constraints in the migration file.

I wanted to check if foreign key constraints were working, so I expected ActiveRecord::InvalidForeignKey to raise it as follows:
It turned out differently than I expected.

student.students_subjects.create!(subject_id:'dummy')
# Enter ActiveRecord::RecordInvalid:Subject

By the way, I thought the problem was that it was a string even though it was an id, so it was the same even if I tried an id that didn't actually exist.

student.students_subjects.create! (subject_id:999)
# Enter ActiveRecord::RecordInvalid:Subject

Looking at the rails formula, I think it's strange because it happens during insert.
https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/InvalidForeignKey.html

I would appreciate it if you could advise me if you know the cause or clue.

ruby-on-rails rails-activerecord

2022-09-30 16:05

1 Answers

Currently, I think it is as follows.
In this case, the student_id (the id of the student present) is automatically required, so
ActiveRecord::RecordInvalid occurs.

class StudentsSubject
  belongs_to —student
end

You can raise the ActiveRecord::InvalidForeignKey because the student_id is no longer required by doing the following:

belongs_to:student, optional:true


2022-09-30 16:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.