I have the following
class User < ApplicationRecord
has_one :physician
end
and
class Physician < ApplicationRecord
belongs_to :user
end
Since a user can only have one physician, I was surprised that multiple physician records can be created with the same user id.
Why is this? And how to I prevent it?
A
belongs_toassociation does not in any way guarantee that the values are unique. It only stipulates that the association is stored in a foreign key on this models table and thus can only have a single value.has_onedoesn't actually provide any guarantees either. It just specifies that this table is referred to on the other table. If there are multiple matching rows on the other table it will chose the last.If you want to enforce uniqueness per table you need a validation:
And a database index to actually guarantee uniqueness on the database level: