rails validation with a combination of keys

156 Views Asked by At

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
1

There are 1 best solutions below

0
prasannaboga On

Write custom validator to check uniqueness.

class Relationship < ActiveRecord::Base
    ...

    validate :follow_unique_users

    def follow_unique_users
        if where('(user_1_id = :user_1_id and user_2_id = :user_2_id) or (user_1_id = :user_2_id and user_2_id = :user_1_id)', {user_1_id: <user_1_id>, user_2_id: <user_2_id>}).exist?
          errors.add(:base, "error message")
        end
    end
end