How to generate sequential number automatically in Rails?

1

I am developing a form for registration in a selective process and after the user send the registration data I would like to generate the registration number in the following format: 00012018. I found only one answer to that but it did not work.

Rails 5.

    
asked by anonymous 29.05.2018 / 23:32

1 answer

1

This 00012018 you want does not have to be persisted, and can be used for viewing only. To do this, you can implement a method in the template.

class Inscricao < ApplicationRecord
  def numero_inscricao
    return nil unless self.persisted?

    id_com_zeros = "%04d" % self.id
    "#{id_com_zeros}#{self.created_at.year}"
  end
end

This will give you:

foo.numero_inscricao
=> "00012018"

As it uses #created_at , it will work for the next years and for the records that are already in the database, because it is a function executed in memory.

Just be sure that the ID is an integer, not a UUID, as is possible.

07.06.2018 / 02:21