pix*_*rth 7 activerecord ruby-on-rails callback
我正在努力做到这一点
has_many :roles, :before_add => :enforce_unique
def enforce_unique(assoc)
false if exists? assoc
end
Run Code Online (Sandbox Code Playgroud)
从文档:"如果before_add回调抛出异常,该对象不会被添加到集合中".上面的使用false不会阻止添加,所以我不得不这样做:
def enforce_unique(assoc)
raise if exists? assoc
end
Run Code Online (Sandbox Code Playgroud)
这样,它确实没有被添加,但它也引发了必须处理的异常.这里对我来说不是很有用.我更喜欢这种行为更像常规AR回调before_save,其中返回FALSE也会阻止保存(或添加),但不会引发异常.
在上面的这种情况下,我宁愿这只是不要静默添加关联.有没有办法做到这一点?我错过了什么?或者在这里提出例外唯一的选择?
如果关联不是多态的,您可以执行以下操作:
validates_uniqueness_of :name_of_model
Run Code Online (Sandbox Code Playgroud)
在 Role 内部,name_of_model 是您关联的内容