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|
break if s.special.to_i != special
special += 1
end
super
write_attribute(:special,special)
end
end
You should overrride
after_initializein your class instead ofinitialize. Overridinginitializedoesn’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.