ruby-on-rails – 验证自引用关联不会链接回rails中的原始实例
发布时间:2020-12-17 03:09:21 所属栏目:百科 来源:网络整理
导读:我有一个多对多模型,遵循 this great railscast中的示例 我的模型将作者彼此联系起来.我想验证作者不能自己交朋友.我知道我可以在UI级别处理这个问题,但是我希望能够进行验证以防止UI中的错误允许它.我试过validates_exclusion_of,但它不起作用.这是我的关系
我有一个多对多模型,遵循
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 解决方法
您必须使用自定义验证:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |