[LRUG] Best way to implement an increasing number?
Srushti Ambekallu
srshti at gmail.com
Fri Apr 19 03:13:36 PDT 2013
Fair enough. And I can see that problem being even worse in a bulk import situation.
How about this?
class A < ActiveRecord::Base
has_many :bs
def next_number
bs.size + 1
end
end
class B < ActiveRecord::Base
belongs_to :a
validates_presence_of :code
before_create :set_code
def set_code
self.code = "#{a.name}-#{'%03d' % a.next_number}"
end
end
In addition to this you'll definitely need to put in a unique constraint on the table bs across code & a_id (that's what the db is for after all), and then catch any failed saves (making sure they are because of a duplicate code) and resetting the code before trying to save again. Basically, I'm trying to remove any saves of A at all.
Thanks,
Srushti
http://c42.in
On 19-Apr-2013, at 3:28 PM, Andrew Stewart wrote:
>
> On 19 Apr 2013, at 11:55, Srushti Ambekallu wrote:
>> And possibly:
>> validates_uniqueness_of :code, :scope => :a_id
>>
>> I'm guessing that would fail the save in code, rather than deadlocking in the DB, and which would then let you handle the error in code and trying another save.
>
> Unfortunately validates_uniqueness_of doesn't really work (it's noted in the Rails docs under 'Concurrency and integrity')...
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
More information about the Chat
mailing list