Search code examples
ruby-on-railsrandominsertrecord

how to add a random id feature on each new record insert in ruby on rails


I have a table which has to do with posts

schema:

id | post_id | user_id | title | content

right now all columns are set and work as intended but now i want to add a unique ID in the post_id column like 7384756291 in each new record insert into the database

how can i add this feature? i guess i can easily create a random ID but the problem is how to make sure its unique from the others before the record is inserted, otherwise create new and try again...


Solution

  • Just keep trying until it doesn't exist:

    post_id = rand(10000000000)
    
    while Model.exists?(:post_id => post_id)
      post_id = rand(10000000000)
    end
    
    Model.create(:post_id => post_id, ...)