2015-09-07 57 views
1

我有一個User模型:Ruby on Rails的 - 自引用關聯:避免創建兩次相同友誼Relatioship

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_id是創建friendship關係的userid)。

我想補充一個validation是不允許創建兩次相同friendship關係(看看下面的例子):

## 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. 

回答

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