if create fails, it still auto increment
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.
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 can you tell me more? If we just move this code to after_create it will create objects with nil id.
@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 so what you propose?
As per this issue, I suggest using after_create instead so that sequences are only assigned to records that will successfully be persisted.
@0sc so you want make it in two transactions? I prefer keep atomicity.
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 it's not ActiveRecord :)
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?
There are no transactions in mongoid :3