How to generate sequential numbers automatically with current year in Rails?

Asked

Viewed 355 times

0

I need that when a new product is created it generates a number ex: 0001/2015 numero/ano_in effect and when it changes year back to zero.

I made a helper just to format the number in the views, but it does not solve the problem of automatic generation and renewal next year.

def format_product_number(product_code)
 format_product = product_code[0..4]
 format_product << "/#{Time.now.year}"
 format_product
end 

I have a form with a field:

@product

<%= f.label :product_number %>
<%= f.number_field :product_number %>

Someone knows a way to do it?

  • 1

    Generate automatico and add in table?

  • 1

    The bank you will use is the same sqlite?

  • @Alextakitani For now yes, I am new not yet the advantages and disadvantages of other banks.

  • @Jeffersonalison Auto generate, type as the ID itself, as soon as the client clicks create generate the "current/ano_number".

  • 1

    Generating the number is relatively simple, the problem is the requirements. Is it a real system? If yes, operates at what times? Can the sequence have holes? ex.: 001/2015, 003/2015 ?

1 answer

1


@Alextakitani made good inquiries, but to respond quickly you can store it in the bank using a callback:

    before_create :record_code_number

    private

    def record_code_number
      self.your_field_table = "#{product_code[0..4]}/#{Time.now.year}"
    end

Always keep in mind the type of callback used, and for validations as well!

Valeuu!

Browser other questions tagged

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