def before_create_save(record)
vouchercode = generate_vouchercode(8)
while Voucher.find(:first, :conditions => {:vouchercode => vouchercode})
vouchercode = generate_vouchercode(8)
end
record.vouchercode = vouchercode
end
Refactorings
No refactoring yet !
Adam
January 6, 2009, January 06, 2009 18:19, permalink
Put those concerns in your model. Something like:
class Voucher < ActiveRecord::Base
before_create :create_vouchercode
protected
def create_vouchercode
self.vouchercode = generate_vouchercode(8)
create_vouchercode if find_by_vouchercode(vouchercode)
end
end
Marc-Andre
January 13, 2009, January 13, 2009 01:49, permalink
...and if you favor using a while over recursion:
def create_vouchercode
begin
self.vouchercode = generate_vouchercode(8)
end while find_by_vouchercode(vouchercode)
end
dive.myopenid.com
January 22, 2009, January 22, 2009 14:13, permalink
nice nice nice thank you all! :-) uhm the magic 8 ... it's a variable to define the length of the vouchercode. but hm since it's always the 8 i coulda remove it ... good point!
Fabien Jakimowicz
February 12, 2009, February 12, 2009 13:34, permalink
If you are using ActiveRecord and if your database supports it you should use unique indexes.
add_index(:vouchers, [:vouchercode], :unique => true)
class Voucher < ActiveRecord::Base
def create_or_update
super
rescue ActiveRecord::StatementInvalid => e
if e.to_s =~ %r{index_vouchers_on_vouchercode}i
self.vouchercode = generate_vouchercode(8)
retry
else
raise
end
end
end
Coming from python, I would say this is pretty straight forward. But knowing some ruby, I suspect there's a DRYer way, right?