mongoid_auto_increment icon indicating copy to clipboard operation
mongoid_auto_increment copied to clipboard

if create fails, it still auto increment

Open bbc4468 opened this issue 12 years ago • 10 comments

I have the following code

class SizeList include Mongoid::Document field :_id, type: Integer field :name auto_increment :sequence, :seed => -1, :step => 1 before_create { self.id = self.sequence } end

I want the sequence to be continuous. This works really well, except in the case when create fails. It should decrease the sequence in such cases.

You should probably use after_add callback to increase the auto increment value.

Although i can still live with it.

bbc4468 avatar Feb 12 '14 16:02 bbc4468

Hi @proton, I'm looking to take this on. What do you think of changing https://github.com/proton/mongoid_auto_increment/blob/master/lib/mongoid_auto_increment.rb#L17 to after_create instead? That way the sequence is only generated when the DB persistence is confirmed

0sc avatar Oct 07 '18 13:10 0sc

@0sc can you tell me more? If we just move this code to after_create it will create objects with nil id.

proton avatar Oct 07 '18 13:10 proton

@proton my understanding is that if create fails the @@incrementor.inc(seq_name, options)) logic never executes and @@incrementor will remain in the state it was in before the creation was attempted. That way only valid/persisted get to have sequence assigned to them.

0sc avatar Oct 07 '18 13:10 0sc

@0sc so what you propose?

proton avatar Oct 07 '18 13:10 proton

As per this issue, I suggest using after_create instead so that sequences are only assigned to records that will successfully be persisted.

0sc avatar Oct 07 '18 13:10 0sc

@0sc so you want make it in two transactions? I prefer keep atomicity.

proton avatar Oct 07 '18 13:10 proton

I'm not sure I understand what you mean. Activerecord callbacks are executed within a single database transaction (See the transaction section here). Maybe I'm missing something but switching from before_create to after_create should not introduce another transaction

0sc avatar Oct 07 '18 13:10 0sc

@0sc it's not ActiveRecord :)

proton avatar Oct 07 '18 14:10 proton

Ahh, my bad I was looking at the wrong docs.

But why will switching from before_create to after_create introduce another transaction in mongoid?

0sc avatar Oct 07 '18 14:10 0sc

There are no transactions in mongoid :3

proton avatar Oct 07 '18 15:10 proton