I have two tables, Assets and Relationships. They look like this (plus other columns I'm omitting for brevity):
# Table name: relationships
#
# id :uuid not null, primary key
# asset1_id :uuid not null
# asset2_id :uuid not null
# type :string not null
# Table name: assets
#
# id :uuid not null, primary key
# type :string not null
# name :string not null
I want relationships of a type between two assets to be unique. So for example, let's say I have a relationship of type membership
.
Relationship.create!(type: 'membership', asset1_id: '61d58a49-86a9-4d7f-b069-2ed1fa27b387', asset2_id: '1856df48-3193-45de-bef0-122cd9f58d7b')
If I try to create that record again, I can easily prevent it with validates :type, uniqueness: { scope: [:asset1_id, :asset2_id] }
and add_index :relationships, [:type, :asset1_id, :asset2_id], unique: true
, however when I use these the following case is not prevented:
Relationship.create!(type: 'membership', asset1_id: '1856df48-3193-45de-bef0-122cd9f58d7b', asset2_id: '61d58a49-86a9-4d7f-b069-2ed1fa27b387')
Note that this is the same as the previous record, only with the order of the asset ids reversed.
How can I prevent this (preferably at the DB level)?