3

I'd like to have organised invoices in this format:

AB20140001

AB is the acronym of our company, 20140001 is the first invoice in 2014.The current quick idea is to add to the table invoices columns year and invoice_number and where would be stored 2014 and the current number of invoice (0001 for the first one).

However, how to keep the column invoice_number in the format XXXX (for the second invoice would be the number 0002 and so on)?

Or - is there a better way to organise invoice numbering?

Thank you in advance.

user984621
  • 46,344
  • 73
  • 224
  • 412

1 Answers1

2

I'd do a function that runs after create and sets the serial number

We used :after_create so that we can use the :id after it was set.

class Invoice < ActiveRecord::Base
  after_create :set_invoice_numeber

  def set_invoice_number
    self.update_attribute(:invoice_number, 'AB' + Time.now.year + '%.4d' % id)
  end

end
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89
  • `id` will be set `after_create`, so he should use that. Also, I assume in 2015 he wants to start with `AB20150001`. Your answer does not provide a solution for that. – Mischa Sep 01 '14 at 13:33
  • TypeError (no implicit conversion of Integer into String). Need convert to string for the year.So it will like `Time.now.year.to_s` – Mada Aryakusumah Apr 12 '21 at 15:00