简体   繁体   English

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

[英]Validating a self-referential association doesn't link back to the original instance in rails

I have a many-to-many model, following the example in this great railscast 我遵循这个伟大的railscast中的示例,有一个多对多模型

My model links authors to each other. 我的模型将作者彼此联系起来。 I'd like to validate that an author cannot friend himself. 我想证明作者不能与自己成为朋友。 I know I can handle this at the UI level, but I'd love to have a validation in place to prevent a bug in the UI from allowing it. 我知道我可以在UI级别上处理此问题,但是我很乐意进行验证,以防止UI中的错误允许它。 I've tried validates_exclusion_of , but it doesn't work. 我已经尝试了validates_exclusion_of ,但是它不起作用。 Here's my model for the relationship: 这是我的关系模型:

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

You'll have to use a custom validation: 您必须使用自定义验证:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM