1

I have a User model and a Catpanion (friend) model. The catpanion model is self-referrential connecting two users together with a requestor_id and a requestee_id through an add friend system. I'm trying to validate that two users are not already catpanions before the catpanion is created for them. I've used:

validates :requestor_id, uniqueness: { scope: :requestee_id }

This will prevent the requestor from adding the same requestee, but the requestee can still add the requestor, essentially creating a duplicate record.

User model:

class User < ApplicationRecord
  has_many :requested_relationships, foreign_key: "requestor_id", class_name: 'Catpanion'
  has_many :requestees, through: :requested_relationships

  has_many :requestees_of_relationships, foreign_key: "requestee_id", class_name: 'Catpanion'
  has_many :requestors, through: :requestees_of_relationships
end

Catpanion model:

class Catpanion < ApplicationRecord
  belongs_to :requestor, class_name: 'User', foreign_key: "requestor_id"
  belongs_to :requestee, class_name: 'User', foreign_key: "requestee_id"

  validates :requestor_id, uniqueness: { scope: :requestee_id }
end

Catpanion schema:

create_table "catpanions", force: :cascade do |t|
  t.integer "requestor_id"
  t.integer "requestee_id"
  t.datetime "created_at", precision: 6, null: false
  t.datetime "updated_at", precision: 6, null: false
  t.index ["requestor_id", "requestee_id"], name: "index_catpanions_on_requestor_id_and_requestee_id", unique: true
end

Note: There is no accept or decline friend option (yet). If one user adds another, the friendship is created for both users.

Hsabes
  • 21
  • 3

0 Answers0