Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Generating random number that does not exist in database

In my application I have a Case model & every case generated by user has a case_number.

case_number is generated from my Case model. Currently Im creating a 3 digit random number from my model after creating a case.

class Case < ActiveRecord::Base

  after_create :random_case_number

  private
    def random_case_number
      random_number = Random.rand(999)
      self.update_attributes(case_number: random_number)
    end
end

This have caused so some of the cases have the same case_number. How can I from my model generate a random number that has not been currently used & if all of the 3 digit numbers are taken, it can move to 4 digits and so on.

like image 876
Rubioli Avatar asked Jul 16 '26 21:07

Rubioli


1 Answers

To generate a random number and ensuring that the number doesn't exist in the database I would do something like this:

before_create :assign_unique_case_number

validates! :case_number, uniqueness: true

private

CASE_NUMBER_RANGE = (10_000..99_999)

def assign_unique_case_number
  self.case_number = loop do
    number = rand(CASE_NUMBER_RANGE)
    break number unless Case.exists?(case_number: number)
  end
end

Please note that the more case there are in the database the longer it might take to find an unused number. Therefore I suggest using greater numbers right from the start. Greater numbers have another advantage: They are harder to guess what might or might not be important in your application.

Furthermore: Rails cannot guarantee that uniqueness in the database. There might be race conditions that lead to duplicates. The only way to avoid that is to add a unique index to the database column in a migration like this:

add_index :cases, :case_number, unique: true
like image 80
spickermann Avatar answered Jul 18 '26 11:07

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!