【发布时间】:2015-09-07 13:36:47
【问题描述】:
我有一个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_id 和friend_id(user_id 是创建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.
【问题讨论】:
标签: ruby-on-rails validation rails-activerecord