2017-06-20 48 views
0

我遇到了Rails的验证器的问题 我有一个表FollowingRelationship来存储几个用户,其中我应该验证follower_id != followed_id(用户不能跟随他们自己) 。在Rails中的几个属性的自定义验证器

这是我的模型:

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

这是否帮助? https://stackoverflow.com/q/2273122/477037 – Stefan

回答

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

我已经为我的Facebook克隆做了这样的验证。

你可以找到它here

基本版本看起来像这样

def stop_friending_yourself 
     errors.add(:user_id, "can't friend themself") if user_id == friend_id 
    end