Search code examples
ruby-on-railsdatabasemodelinitializationunique

Rails create unique value for saving in database


I mean not to check on saving is current value - unique.

How can I create value (for example in my model), check is it unique for my table. Anf id not than try to create new value maybe. And check the uniqueness again

Now I have the following code in my model:

  after_initialize :init

  def init
    self.some_field = rand(1..99_999_999).to_s
  end

Solution

  • You can use model callback like,

    before_create :generate_some_field
    
    def generate_some_field
      self.some_field = loop do
        random = rand(1..99_999_999).to_s
        break random unless ModelName.exists?(some_field: random)
      end
    end