两条路上的2列唯一性

时间:2017-02-10 06:42:32

标签: ruby-on-rails activerecord

我有一个friendship模型,用于存储2 user的ID。

user_id  friend_id
  1          2
  3          4

我想阻止以下条目。用户1& 2已在关系中定义。因此,添加其他条目,例如2&应该避免使用1

user_id  friend_id
  1          2
  2          1

我尝试过以下但不完全符合我的要求。它只能确保用户不能两次添加同一个朋友。

class Friendship < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, :class_name => "User"

    validates_uniqueness_of :user_id, scope: :friend_id
    validates_uniqueness_of :friend_id, scope: :user_id

    validate :check_friend_and_user # prevent user trying to add him/herself as friend.

    def check_friend_and_user
      errors.add(:friend, "can't be the same as user") if user == friend
    end
end

0 个答案:

没有答案