Dercni
Dercni

Reputation: 1224

Custom validation not triggering rollback

I have a model with standard and a custom validtion

The custom validation works and does it's job correctly, however...

When I save within a transaction and trigger my custom validation the save fails but the transaction is not rolled back.

When I save within a transaction and trigger a system validation the save fails AND the transaction is rolled back.

I have read I can check the use the save bang and then trigger an exception to rollback the transaction however I'd prefer my custom validation to function the same as the system validations without needing an exception handler.

My custom validation code is simply:

class Family < ActiveRecord::Base
  validates_presence_of :name
  validate :ensure_no_twins

  Private
    def ensure_no_twins
      errors.add(:name, "A sibling by this name already exists") if self.siblings.exists?(name: name) rescue true
    end
end

Upvotes: 1

Views: 694

Answers (1)

Josh
Josh

Reputation: 8586

Have you tried it without the rescue clause? It may be catching an exception that it's not supposed to be catching?

errors.add(:name, "A sibling by this name already exists") if self.siblings.exists?(name: name)

Upvotes: 2

Related Questions