A
A
Andriy Stepanyuk2015-10-26 14:21:22
Ruby on Rails
Andriy Stepanyuk, 2015-10-26 14:21:22

Autogenerate id when id is primary key string?

Good afternoon, the question is, how best to auto-generate id when it is a string?
migration:

def change
    create_table :names, id: false do |t|
      t.string :id, limit: 21, null: false
      ...
    end
    add_index :names, :id, unique: true
end

In the model, respectively:
class Name < ActiveRecord::Base
  self.primary_key = :id
  before_create :set_id

private
  def set_id
    if self.id.blank?
      for attemps in 0..3
        self.id = generate_id
        return if Name.find_by(id: self.id).nil?
      end
    end
  end
end

The generate_id function generates a random string id of 21 characters long using SecureRandom.
Obviously, this solution may fail with an exception if the same id is generated at the same time, or if the number of attempts is not enough. In connection with this question: how to make what would be reliable? I understand that the probability that this solution of mine will fail is negligible, but nevertheless I wonder which way is correct.
I read the article:
ruby-journal.com/how-to-override-default-primary-k...
There the author recommends not doing execute %Q{ ALTER TABLE "products" ADD PRIMARY KEY ("sku"); }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rutaka nashimo, 2015-10-26
@rutaka_n

I don’t quite understand why make id a string, but if you just need a unique string value, then you can use uuid

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question