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