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

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

我有一个多对多模型,遵循 this great railscast 中的示例

我的模型将作者彼此联系起来。我想证实作者不能与自己交 friend 。我知道我可以在 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

最佳答案

您必须使用自定义验证:

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

关于ruby-on-rails - 验证自引用关联不会链接回 rails 中的原始实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3169664/

相关文章:

ruby-on-rails - Rails/Rspec : Testing delayed_job mails

ruby-on-rails - 如何修复错误 URI(不是 URI?): nil

mysql - 在多对多相关表中进行高效搜索

java - 批量插入多对多关系

python - 选择订阅特定用户但该用户未订阅的所有用户

html - Ruby on Rails 链接、导航

ruby-on-rails - `rake notes` 应该扫描haml

php - 检查数组键是否存在,不区分大小写

Javascript验证两个文本框

reactjs - 在 react 中验证 Ant 设计 InputNumber 的最大长度