Ruby On Rails - 自引用关联:避免创建两次相同的友谊关系

时间:2015-09-07 13:36:47

标签: ruby-on-rails validation rails-activerecord

我有User型号:

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

Friendship模型:

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

Friendship表包含user_idfriend_iduser_idid的{​​{1}},可创建user关系)。

我想添加一个不允许创建两次相同friendship关系的validation(请看下面的示例):

friendship

1 个答案:

答案 0 :(得分:1)

你应该写一个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