foliwe83
foliwe83

Reputation: 590

generate UUID on object creation in rails

I want to generate a unique ID when a new object is to create

I have a model called Product, which has a name and weight and price. I want to create a unique Id that begins with "TPK" + random 8 characters and add it to the products table. what's a simple method to achieve it?

Here is the current migration file

class Products < ActiveRecord::Migration[5.2]
 def change
  create_table :products do |t|
  t.string :weight
  t.string :product_name
  t.integer :price
  .......

I want to add another attribute to it called product_code and I want it to have a unique Id on creating starting with "TPK" + random 8 characters

Upvotes: 0

Views: 1774

Answers (1)

EJAg
EJAg

Reputation: 3298

I'd recommend using migration only to update the Schema and leave the model logics inside the model. So first, you create a migration to add product_code to the products table. Then add a hook in Product model to create a default code:

class Product < ApplicationRecord
  before_create :default_product_code

  private
  def default_product_code
    #your implementation
    #e.g. self.product_code = 'TPK' + SecureRandom.hex(4)
  end
end

Upvotes: 1

Related Questions