【问题标题】:rails validation with a combination of keys使用组合键进行 rails 验证
【发布时间】:2018-08-07 16:38:01
【问题描述】:

我有一个带有多对多自连接表的用户模型,如下所示

class User < ActiveRecord::Base
   has_many :follower_relationships, foreign_key: :user_2_id, class_name: 'Relationship'
   has_many :followee_relationships, foreign_key: :user_1_id, class_name: 'Relationship'
   has_many :followers_all, through: :follower_relationships, source: :user_1
   has_many :followees_all, through: :followee_relationships, source: :user_2

使用以下模型创建连接

class Relationship < ActiveRecord::Base
    belongs_to :user_1, class_name: 'User', foreign_key: :user_1_id
    belongs_to :user_2, class_name: 'User', foreign_key: :user_2_id

简而言之,一个用户可以有很多关注者,也可以关注很多用户。当 UserA 跟随 UserB 时,将创建一条关系记录,其中 user_1 = UserA 和 user_2 = UserB。

我需要实施唯一性验证,以确保 UserA 和 UserB 之间仅存在一条记录。因此,如果记录存在

user_1 == UserA AND user_2 == UserB 

那么在哪里不应该存在其他关系

Either

user_1 == UserA and user_2 == UserB 

OR

user_1 == UserB and user_2 == UserA

【问题讨论】:

    标签: validation ruby-on-rails-4 activerecord custom-validators


    【解决方案1】:

    编写自定义验证器来检查唯一性。

    class Relationship < ActiveRecord::Base
        ...
    
        validate :follow_unique_users
    
        def follow_unique_users
            if where('(user_1_id = :user_1_id and user_2_id = :user_2_id) or (user_1_id = :user_2_id and user_2_id = :user_1_id)', {user_1_id: <user_1_id>, user_2_id: <user_2_id>}).exist?
              errors.add(:base, "error message")
            end
        end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 2012-01-24
      • 1970-01-01
      • 2011-12-17
      • 2015-10-03
      • 2023-04-10
      • 1970-01-01
      • 2011-02-01
      相关资源
      最近更新 更多