我遇到了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)
不應該創建記錄,但它的作品。
任何人都可以幫助我嗎?謝謝。
這是否幫助? https://stackoverflow.com/q/2273122/477037 – Stefan