79456668

Date: 2025-02-21 07:53:21
Score: 0.5
Natty:
Report link

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

Reasons:
  • Blacklisted phrase (0.5): THANKS
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Md Aqib