Ich bin in Schwierigkeiten mit Rails 'Validator' Ich habe eine Tabelle FollowingRelationship
, um ein paar Benutzer zu speichern, in denen ich validieren sollte, dass follower_id != followed_id
(Benutzer kann nicht folgt) .benutzerdefinierte Validator auf ein paar Attribut in Rails
Das ist mein Modell:
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
aber der Prüfer noch nicht funktioniert
FollowingRelationship.create(:follower_id => 1, :followed_id => 1)
den Datensatz nicht schaffen sollte, aber es funktioniert.
Konnte mir jemand helfen? Vielen Dank.
hilft das? https://stackoverflow.com/q/2273122/477037 – Stefan