Last active
January 2, 2016 16:49
-
-
Save mrbrdo/8333070 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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