Since 1.1.0, Rails includes grouping and calculation functions. maximum is what we want to use here.

The system I am building has many users, and each user has it’s own invoice number sequence. Here is the code in it’s entirity:

app/models/invoice.rb
1 class Invoice < ActiveRecord::Base
2   belongs_to :user
3 
4   def self.find_next_available_number_for(user, default=999)
5     (user.invoices.maximum(:no) || default).succ
6   end
7 end

This code is pretty simple to read. In fact, in English, it translates to:

Find the maximum value of no in invoices for user, or use the default value, and then take the successor of this value.

You see, Ruby code is so much more succint !

Anyway, the features used in this article were:

Search

Your Host

A picture of me

I am François Beausoleil, a Ruby on Rails and Scala developer. During the day, I work on Seevibes, a platform to measure social interactions related to TV shows. At night, I am interested many things. Read my biography.

Top Tags

Books I read and recommend

Links

Projects I work on

Projects I worked on