views:

72

answers:

3

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...

+1  A: 

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.

Beerlington
+3  A: 

Try after_save.

Jonathan Julian
As mentioned by Beerlington, the id is nil until save occurs.
Sam C
A: 

Where would you like such a printed statement to show up? in the console? in a view?