4

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???

Adrian
  • 9,102
  • 4
  • 40
  • 35

1 Answers1

0

You need to catch the exception from whatever code is adding the permission role.

begin
  role.permissions.add(permission)
rescue
  # do whatever should happen here.
end

Although, you may want to check that the permission exists before trying to add it.

Joe Van Dyk
  • 6,828
  • 8
  • 57
  • 73