How do I auto-increment a unique version number using ActiveRecord?
I have a model License
that needs to have a version number开发者_JS百科 (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?
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
精彩评论