[LRUG] Best way to implement an increasing number?

Jonathon Horsman jonathon at arctickiwi.com
Fri Apr 19 02:10:53 PDT 2013


Hi Andy

Any reason not to use

before_validation :set_code

rather than

after_create :set_code

and set_code method merely sets the value on the object rather than hit the
database a second time?

Also presumably you should have

validates_presence_of :code

Regards


On 19 April 2013 09:51, Andrew Stewart <boss at airbladesoftware.com> wrote:

> 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
>
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>



-- 
Jonathon Horsman
Director
Arctic Kiwi
Mobile: 079 42366038
Web: http://www.arctickiwi.com
Twitter: @jhorsman <http://www.twitter.com/jhorsman>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20130419/5ea05a88/attachment-0003.html>


More information about the Chat mailing list