[LRUG] Best way to implement an increasing number?

Andrew Stewart boss at airbladesoftware.com
Fri Apr 19 01:51:28 PDT 2013


Hello El Rug,

Today's question sounds simple – and probably is – but I seem to have answered it wrongly in my code.

I have two classes A and B, where A has many Bs and B belongs to A.

B has a `code` method which returns a candidate key (I think that's the correct term), i.e. a unique identifier.  It has some domain-meaningful text and a number.  The number is what distinguishes the codes of two Bs belonging to the same A.  Once a B's code is set at creation it must not change.

My current implementation looks like:

    class A < ActiveRecord::Base
      has_many :bs

      def next_number
        increment! :number
        number
      end
    end

    class B < ActiveRecord::Base
      belongs_to :a
      after_create :set_code

      private

      def set_code
        update_attributes code: "#{a.name}-#{'%03d' % a.next_number}"
      end
    end

This has been working when adding Bs individually but recently I introduced bulk import of Bs from spreadsheets.  During imports in production I've begun to see MySQL deadlocks such as:

#<ActiveRecord::StatementInvalid: Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: UPDATE `as` SET `number` = 193, `updated_at` = '2013-04-19 07:40:29' WHERE `as`.`id` = 3025>

There must be a better way to do this...?

Thanks in advance,

Andy Stewart





More information about the Chat mailing list