Skip to content

Instantly share code, notes, and snippets.

@clemens clemens/invoice.rb
Created Jul 24, 2014

Embed
What would you like to do?
invoice number generation per year
class Invoice < ActiveRecord::Base
before_validation :generate_number, on: :create
private
def generate_number
prefix = "R#{Date.today.strftime('%y')}-"
last_order_number_this_year = self.class.where("number LIKE ?", "#{prefix}%").order("number DESC").limit(1).pluck(:number).first
number = last_order_number_this_year ? last_order_number_this_year.match(/\A#{prefix}(\d+)\z/)[1].to_i : 0
self.number = "#{prefix}#{sprintf('%05d', number + 1)}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.