Get ID of Rails Model before saving...?

Usually when people think they need to do this they actually do not need to do it. Like John says, explain what you are trying to do and someone can probably suggest a way to do it without having to know the id in advance.


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.


I was looking for this too, and I found an answer:

Let's suppose model name is "Model" and table name is "models"

model.rb

before_save {
    next_id=Model.connection.select_value("Select nextval('models_id_seq')")
}

This will output the value your record will take for id IF it gets saved