Omar Lahlou
Omar Lahlou

Reputation: 1000

Ruby On Rails - Self-Referential association: Avoid creating twice the same Friendship Relationship

I have a User model:

has_many :friendships, dependent: :destroy
has_many :friends, through: :friendships
has_many :inverse_friendships, class_name: "Friendship", foreign_key: "friend_id", dependent: :destroy
has_many :inverse_friends, through: :inverse_friendships, source: :user

And a Friendship model:

belongs_to :user
belongs_to :friend, class_name: "User"

Friendship table has both user_id and friend_id(user_id is the id of the user that creates the friendship relationship).

I want to add a validation that disallows creating twice the same friendship relationship (look at the example below):

## first_user has id = 103
## second_user has id = 209
## I don't want to have:
Frienship<id = 1072, user_id = 103, friend_id = 209>
Frienship<id = 3022, user_id = 209, friend_id = 103>
## i.e, I don't want to store this relationship two times.

Upvotes: 1

Views: 146

Answers (1)

dimakura
dimakura

Reputation: 7655

You should write a custom validator:

class Friendship < ActiveRecord::Base
  validate :friendship_validation

  private

  def friendship_validation
    if Friendship.where("(user_id=? AND friend_id=?) OR (user_id=? AND friend_id=?)", self.user_id, self.friend_id, self.friend_id, self.user_id).any?
      errors.add(:friendship, "friendship exists")
    end
  end
end

Upvotes: 1

Related Questions