store the formatted value of my created_at date in the ID

Asked

Viewed 35 times

3

I have one question: A column called shoe_id on my table, I’d like that id is automatically generated when I register a product, and I would also like it to be in the format without dividers from the creation date, for example: what I want to implement in the Browser happens when in the console I do

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

how can I do this?

1 answer

1

how to do this is using callbacks , where in the object creation action (after_create), you will set this value to the field shoe_id, so 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
  • I thought about using before_create and changing the way to get the current creation date, such as joining Time.now with Data.now for example, or in the latter cases, instead of using to_formatted_s(:number), using . gsub(/ D/, '), however, I believe that in the last line it will have to do the code as follows: [lself.update(shoe_id: created_at.to_s.gsub(/ D/, ')] ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.