2017-06-20 3 views
0

私はRailsのバリデーターに問題があります 私はfollower_id != followed_id(ユーザーは自分自身に従うことはできません)を検証する必要があるユーザーの数を格納するテーブルFollowingRelationshipを持っています。 。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 
関連する問題