Last active
August 29, 2015 14:10
-
-
Save selvan/9312aadd033fdebbf78f to your computer and use it in GitHub Desktop.
Rails DB Sequence Generation
This file contains hidden or 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
class CreateMerchantUniqIdGens < ActiveRecord::Migration | |
def change | |
create_table :merchant_uniq_id_gens do |t| | |
t.integer :count, :null => false | |
end | |
# Set initial count to 100 | |
single_row = MerchantUniqIdGen.new | |
single_row.count = 100 | |
single_row.save! | |
end | |
end | |
class MerchantUniqIdGen < ActiveRecord::Base | |
def self.next | |
curr_count = 0; | |
MerchantUniqIdGen.transaction do | |
id_gen = MerchantUniqIdGen.lock(true).first | |
id_gen.count += 1 | |
curr_count = id_gen.count | |
id_gen.save! | |
end | |
curr_count | |
end | |
end | |
puts MerchantUniqIdGen.next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment