Get ID of Rails Model before saving…?

后端 未结 10 1224
鱼传尺愫
鱼传尺愫 2020-12-16 13:03

How do you get the id of a rails model before it is saved?

For example, if I create a new model instance, how can I get its ID before it is saved?

I know t

10条回答
  •  失恋的感觉
    2020-12-16 13:27

    This is less a Rails question and more a database question. This is a problem that will present itself in any web application framework, and the solution is the same in all places. You have to use a database transaction.

    The basic flow will work like this.

    • Open a transaction
    • Save your model
    • Use the ID assigned by the database
    • If it turns out you actually don't want to keep this model in the database, roll back the transaction.
    • If it turns out you want to keep the model in the database, commit the transaction.

    The main thing you will notice from this approach is that there will be gaps in your IDs where you rolled back the transaction.

提交回复
热议问题