2017-06-20 47 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