I have a user model with a many to many self join table like following
class User < ActiveRecord::Base
has_many :follower_relationships, foreign_key: :user_2_id, class_name: 'Relationship'
has_many :followee_relationships, foreign_key: :user_1_id, class_name: 'Relationship'
has_many :followers_all, through: :follower_relationships, source: :user_1
has_many :followees_all, through: :followee_relationships, source: :user_2
The join is created with the following model
class Relationship < ActiveRecord::Base
belongs_to :user_1, class_name: 'User', foreign_key: :user_1_id
belongs_to :user_2, class_name: 'User', foreign_key: :user_2_id
In a nutshell, a user can have many followers and can follow many users. When UserA follows UserB, a relation record is created with user_1 = UserA and user_2 = UserB.
I need to implement a uniqueness validation which will make sure that only one record exists between UserA and UserB. So if a record exists with
user_1 == UserA AND user_2 == UserB
then no other relation should exist where
Either
user_1 == UserA and user_2 == UserB
OR
user_1 == UserB and user_2 == UserA
Write custom validator to check uniqueness.