开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜