Answer the question
In order to leave comments, you need to log in
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
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
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question