I beleive allow_nil: true
will not work as we expect, Because it
create database query:
select 1 as one from table_name
where table_name.column_name is null # Column needs to be validated
and table_name.id != current_object_id limit 1;
So rails finds another record where column_name IS NULL
and it mistakenly thinks the uniqueness is voilated
So according to me the better approach will be
validates :column_name, uniqueness: true, if: -> { column_name.present }
This approach will completely skip the uniqueness validation when column_name value is not present and rails will not run the uniqueness query for nil
value, avoiding false uniqueness error.
THANKS