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

时间:2010-07-02 23:22:57

标签: ruby-on-rails validation many-to-many self-reference

我有一个多对多模型,遵循this great 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

1 个答案:

答案 0 :(得分: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