How to generate sequential number automatically in Rails?

Asked

Viewed 138 times

1

I am developing a form for registration in a selection process and after the user submit 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 didn’t work.

Rails 5.

  • 1

    Give more information, such as codes you have tried so far.

  • You will need to identify what the pattern is in the registration number. In the number you have placed there are 8 characters, then there is a number (1) and then there is the year(2018). Here you will contact this information.

1 answer

1


That one 00012018 that you want does not need to be persisted, and can be used only for visualization. To do this, you can implement a method in the model.

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

That’ll give you:

foo.numero_inscricao
=> "00012018"

How he uses the #created_at, will work for the next years and for the records that are already in the bank, for being a function executed in memory.

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

  • Vlwsssssss, it worked///

Browser other questions tagged

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