Forgetting about Protokoll for the moment, i think this should work.
class Vendor
before_create :set_unique_vendorid
def set_unique_vendorid
if last_vendor = Vendor.find(:last, :order => "id", :conditions => ["vendorid like ?", "#{self.city}%"])
last_vendorid_number = last_vendor.vendorid.scan(/\d+$/).first.to_i
new_vendorid_number = last_vendorid_number + 1
else
new_vendorid_number = 1
end
self.vendorid = "#{self.city}#{sprintf("%03d", new_vendorid_number)}"
end
the sprintf
bit will convert new_vendorid_number into a three-digit string (eg "002") which it looked like you had as a requirement.
NOTE: you have a potential race condition here if you have a server running multiple instances of rails, and two of them try to create a new Vendor object at the same time. But if you get to the point where you're so successful you need to worry about this then you can refactor it with transactions or something :O