我遇到了Rails' Validator'
我有一个表FollowingRelationship
来存储几个用户,我应该在其中验证follower_id != followed_id
(用户无法自己跟踪)。
这是我的模特:
class FollowingRelationship < ApplicationRecord
belongs_to :followed, class_name: "User"
belongs_to :follower, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true, followed_id: true
validates_uniqueness_of :follower_id, scope: :followed_id
class FollowedValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, "User can't follow itselves" unless record.follower_id != value
end
end
end
但验证器仍无法正常工作
FollowingRelationship.create(:follower_id => 1, :followed_id => 1)
不应该创建记录,但它有效。
有人能帮帮我吗?感谢。
答案 0 :(得分:1)
构建自定义验证器类对于单个方法验证来说有点多(除非需要在多个模型中使用)。试试这个
class FollowingRelationship < ApplicationRecord
belongs_to :followed, class_name: "User"
belongs_to :follower, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true, followed_id: true
validates_uniqueness_of :follower_id, scope: :followed_id
validate :does_not_follow_self
def does_not_follow_self
self.errors.add attribute, "User can't follow itself" unless self.follower != self.followed
end
end
答案 1 :(得分:1)
我为我的facebook克隆做了这样的验证器。
你可以找到它here。
基本版本看起来像这样
def stop_friending_yourself
errors.add(:user_id, "can't friend themself") if user_id == friend_id
end