1

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

2
  • Where would you like such a printed statement to show up? in the console? in a view?
    – user94154
    Commented Feb 10, 2010 at 7:47
  • The question is: What do you need it for? If you need it beforehand for some reason, probably something is wrong with your application design or your understandings of ActiveRecord.
    – hurikhan77
    Commented Feb 10, 2010 at 21:41

2 Answers 2

3

Try after_save.

1
  • As mentioned by Beerlington, the id is nil until save occurs.
    – Sam Coles
    Commented Feb 10, 2010 at 9:38
1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.