database – store the formatted value of the date of my created_at in the id

Question:

I have a question: A column called shoe_id was created in my table, I would like this id be generated automatically when I register a product, and I would also like it to be in the format without divisors from the creation date, for example: what I want to implement in Browser happens when in console I do

shoes =  Shoe.new(:shoe_id => shoes.created_at.to_formatted_s(:number))
shoes.save

how can I do this?

Answer:

way to do this is using callbacks , where in the object's create action ( after_create ), you will set this value to the shoe_id field, like this for example:

class Shoe < ActiveRecord::Base

  after_create :generate_shoe_id

  def generate_shoe_id
    self.update(shoe_id: created_at.to_formatted_s(:number))
  end
end
Scroll to Top
AllEscort