4

この素晴らしい Railscastの例に従って、私は多対多のモデルを持っています

私のモデルは著者同士を結びつけます。著者が自分自身を友達にできないことを検証したいと思います。これを UI レベルで処理できることはわかっていますが、UI のバグによってそれが許可されないように、検証を実施したいと考えています。validates_exclusion_ofを試しましたが、うまくいきません。関係の私のモデルは次のとおりです。

class Friendship < ActiveRecord::Base
  # prevent duplicates
  validates_uniqueness_of :friend_id, :scope => :author_id
  # prevent someone from following themselves (doesn't work)
  validates_exclusion_of :friend_id, :in => [:author_id]

  attr_accessible :author_id, :friend_id
  belongs_to :author
  belongs_to :friend, :class_name => "Author"
end
4

1 に答える 1

7

カスタム検証を使用する必要があります。

class Friendship < ActiveRecord::Base
  # ...

  validate :disallow_self_referential_friendship

  def disallow_self_referential_friendship
    if friend_id == author_id
      errors.add(:friend_id, 'cannot refer back to the author')
    end
  end
end
于 2010-07-02T23:48:55.277 に答える