0

I have a model License that needs to have a version number (an Integer) but I don't want that to be confused at all with the actual id.

I have a field version_number. What is the simplest way to tell ActiveRecord to automatically increment it on creation?

Dave Sag
  • 13,266
  • 14
  • 86
  • 134
  • How thread-safe does this need to be? We've found that with multiple Rails processes running over multiple servers, the only way to generate truly unique version numbers was to delegate the generation to an external service; in our case using a Postgres sequence. – Graham Savage Oct 01 '11 at 07:17
  • Not very in the this case. Licenses won't be updated a lot – Dave Sag Oct 01 '11 at 23:44

1 Answers1

1

Use a before_create callback to set version_number to the last version + 1:

class License < ActiveRecord::Base
  before_create :set_version
  ...
  def set_version
    license = License.last
    current_version = license.nil? ? 0 : license.version_number
    self.version_number = current_version + 1
  end
  ...
end
Adam Eberlin
  • 14,005
  • 5
  • 37
  • 49