Validating uniqueness of a particular value in Ecto

Hi!

I have this database table where I keep nationalities of users and I applied a unique_index between user id and the country code for its nationality so there wouldn’t be duplicates.

Then I created a citext field to determine different characteristics of these nationalities, one of them marking it being the place of birth.

So I wanted to validate making it sure you could have multiple nationalities, but only one of them having this particular field marked as a place of birth.

I this something I can (or should) achieve using changeset validations?

Thanks!

You can put the uniqueness validation entirely inside the DB and then you can point Ecto at the name of the DB constraint. Worked fine every time I did it.

You could have two association between User and Nationality. One is a many to many, while the other is a belong to (place of birth).

You can set a unique constraint on the join table for many to many… user_id, nationality_id to ensure You don’t have duplicate.

You need also to ensure place of birth is not in nationalities, with a custom validation.