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_id
和friend_id
(user_id
是創建friendship
關係的user
的id
)。
我想補充一個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.