I'm trying to cancel the save (gracefully) of a has_many element if is repeated. This is what I mean:
class AdmininstratorRole < ActiveRecord::Base
has_many :permissions, before_add: :avoid_repetition
def avoid_repetition(permission)
raise "Repeated Permission" if self.permissions.where(klass: permission.klass, action: permission.action).count > 0
end
end
If it wouldn't be an associated callback I could just return false and that would cancel the save. But since is an associated callback I need to raise an exception to cancel the saving as explained here. The problem is that I don't know how to recover gracefully from that exception.
Any ideas???