Skip to content

Instantly share code, notes, and snippets.

@mrbrdo
Last active January 2, 2016 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrbrdo/8333070 to your computer and use it in GitHub Desktop.
Save mrbrdo/8333070 to your computer and use it in GitHub Desktop.
# Add a unique index in your migrations like this:
# add_index :table, :code, unique: true
before_create :set_code
around_save :save_with_unique_code
def self.generate_code
SecureRandom.hex(2).upcase
end
def set_code(force = false)
self.code = self.class.generate_code if code.nil? || force
end
def save_with_unique_code
begin
self.class.connection.execute("SAVEPOINT before_record_create;")
yield
# NOTE: be careful if you have other unique fields!
rescue ActiveRecord::RecordNotUnique
set_code(true)
self.class.connection.execute("ROLLBACK TO SAVEPOINT before_record_create;")
retry
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment