sabat
sabat

Reputation: 31

Rails 3 Migration: Autoincrement on (Non-Primary-Key) Column?

I'm looking for a way to create a column that autoincrements the way the automatic :id column does. I could probably handle this somehow in the model, but that seems kludgey. I haven't found anything in stock Rails 3 that handles this; are there gems available that might handle this? I'm surprised it's not already an option, since Rails handles this behavior for primary key columns.

Upvotes: 3

Views: 2221

Answers (2)

nathanvda
nathanvda

Reputation: 50057

Normally auto-incrementing columns are implemented using database sequences. The advantage of using a sequence over calculating the next increment, is that getting the next value from a sequence is atomic. So if you have multiple processes creating new elements, the sequence will make sure your numbers are really unique.

Sequences can be used in postgresql, oracle, mysql, ...

How to implement this, if you are using postgres for instance:

  • select the next value from the sequence:

    Integer(Operator.connection.select_value("SELECT nextval('#{sequence_name}')"))

  • create a sequence:

    Operator.connection.execute("CREATE sequence #{sequence_name}")

  • set the start-value of a sequence :

    Operator.connection.execute("SELECT setval('#{sequence_name}', #{new_start_serial})")
    

Hope this helps.

Upvotes: 1

allesklar
allesklar

Reputation: 9600

If you really think you need this you could create a before_create filter in the model to check the last record attribute value and add 1 to it. Feels hacking though.

Upvotes: 0

Related Questions