【问题标题】:Ruby On Rails - Self-Referential association: Avoid creating twice the same Friendship RelationshipRuby On Rails - 自引用关联:避免创建两次相同的友谊关系
【发布时间】: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_idfriend_iduser_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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      相关资源
      最近更新 更多