ratan
ratan

Reputation: 429

how to print out autoincrement ID in Activerecord model

I have a before_save in my model

before saving the record to the database...I'd like to print out the autoincremented ID that will be inserted. My table has a column id in it.

I tried

before_save :printId

def printId
   puts "ID that will be inserted is: " + self.id
end

this does not work...

Upvotes: 1

Views: 646

Answers (2)

Jonathan Julian
Jonathan Julian

Reputation: 12264

Try after_save.

Upvotes: 3

Peter Brown
Peter Brown

Reputation: 51697

The autoincrement ID does not exist for an ActiveRecord object until it has been saved. It's possible to get the next autoincrement ID for a table, but this doesn't guarantee that the ID will be given to your object when saved since another record may have been added in the meantime.

Upvotes: 1

Related Questions