开发者

Activerecord default accessors & unusual requirements

开发者 https://www.devze.com 2022-12-27 05:59 出处:网络
I have an ActiveRecord::Base class which needs to have one field\'s value picked as the lowest integer available considering the records already in the database. This snippet does that, does it seem e

I have an ActiveRecord::Base class which needs to have one field's value picked as the lowest integer available considering the records already in the database. This snippet does that, does it seem efficient to you? Can it be improved?

class Thing < ActiveRecord::Base
  def initialize
    special = 0
    Thing.find(:all,:order=>"special ASC") do |s|
     开发者_C百科 break if s.special.to_i != special
      special += 1
    end

    super
    write_attribute(:special,special)
  end
end


You should overrride after_initialize in your class instead of initialize. Overriding initialize doesn't always work as expected.

As for automatic value generation, I think the best option would be to use an auto-increment column in the database, because I'm not sure how you would deal with concurrency issues otherwise. This would result in gaps in the used values when rows are deleted of course, so I don't know if that's going to work for you.

0

精彩评论

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