On Wed, Feb 8, 2012 at 10:39 AM, Colin Law <[email protected]> wrote:

> On 8 February 2012 07:12, Bob Smith <[email protected]> wrote:
> > I need a way to set a counter that will show how many of the model
> > have been created and put this in each instance. This will allow me to
> > use the record number as an input to another field before id is set.
> > After things are settled, the real id number can be substituted for
> > the counter.
>
> If you do that and two users come along at the same time and make new
> objects then they will both get the same number.  Can you not just use
> a before_save filter to set the field?  If you think not can you
> explain what you are trying to do (and why) in more detail as there is
> almost certainly a better solution.
>

Maybe the OP really wants a "sequence" (a guaranteed unique number
that is more or less monotomically going up).

The OP may be used to the concept that the primary ID of a record upon
creation is such a sequence. But maybe he needs that number _before_
the record is saved. (e.g. to set a serial number that is saved in the
record).

If that is the business requirement, 3 solutions:

1) don't do it that way. Use a separate sequence generator (which exists
in Postgresql and probably in all databases) and use that to calculate
the unique and more or less monoticly increasing serial number. Do NOT
couple that "business id" with the actual internal database id.

2) If you want to use the database id, then you could use an external
sequence generator and set the Object.id manually before saving (than
configure your db in a way that the primary key is set from the
application).

3) do an after_create  (create the object with most data filled in, the
create will generate the database id and in the after_create calculate
the other field (e.g. serial number) and save again ... this is then an
"update" so the "after_create" will not be triggered again). You may
need some more tricks to make sure this "serial number" field cannot
be modified, otherwise it could be out of sync with you internal database
id (that is "back to (1) above" don't link the "serial number" with the
database id, just make it a separate column with a unique index and
use a separate sequencer to generate those unique codes).

HTH,

Peter

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to