Scenario:
- User can have many Roles
- 3 Models: User -< Userrole >- Role
- User+Userrole are created using the "nested models" approach (accepts_nested_attributes_for)
- Validation fails with: "Userroles user must exist"
Models:
class User < ApplicationRecord
has_many :userroles
accepts_nested_attributes_for :userroles
end
class Userrole < ApplicationRecord
belongs_to :user, optional: true # <--- This seems to be required and disables the foreign_key check
belongs_to :role
end
class Role < ApplicationRecord
has_many :userroles
end
The failed validation seems to be the result of how Devise interacts with Rails 5's enforced foreign_key presence validation. (I wrote a test script that represents this situation, but as a "pure" version, not based on/including the Devise account creation mechanism - the script passed without errors (change the file extension from .txt to .rb): record_creation_test_script.txt)
The mode Userrole thus currently requires "optional: true" and therefor disables the foreign_key check.
Scenario:
Models:
The failed validation seems to be the result of how Devise interacts with Rails 5's enforced foreign_key presence validation. (I wrote a test script that represents this situation, but as a "pure" version, not based on/including the Devise account creation mechanism - the script passed without errors (change the file extension from .txt to .rb): record_creation_test_script.txt)
The mode Userrole thus currently requires "optional: true" and therefor disables the foreign_key check.