验证自引用关联不会链接回rails中的原始实例

Chr*_*lay 4 validation many-to-many ruby-on-rails self-reference

我有一个多对多模型,遵循这个伟大的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
Run Code Online (Sandbox Code Playgroud)

Pär*_*der 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
Run Code Online (Sandbox Code Playgroud)