'Still getting NotNullViolation despite belongs_to :foo, optional: true
I have a has_one
and belongs_to
association, like so:
# teacher.rb
has_one: :student
and
# student.rb
belongs_to :teacher, optional: true
but when I try to create a student without a teacher...
a = Student.new()
a.save!
ActiveRecord::NotNullViolation: PG::NotNullViolation: ERROR: null value in column "teacher_id" violates not-null constraint
Which doesn't make sense, since I have optional: true
. I have tried rake db:drop db:create db:migrate db:seed
numerous times but still the same error
Solution 1:[1]
Thanks to @dbugger and @Daniel Sindrestean and with help from another forum I see it's as simple as going into the existing migration file and changing null: false
to null: true
. Then remake the database. Or run a migration to change null:true
if working on an existing app. Either way, null: false
needs to be null: true
Also, from @max's comment:
The
optional
and its inverserequired
options forbelongs_to
just control if the association adds apresence_of
validation. That really does not have anything to with a database driver error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |