views:

205

answers:

2

I am a little confused about the auto-increment id field in rails. I have a rails project with a simple schema. When i check the development.sqlite3 I can see that all of my tables have an id field with auto increment.

CREATE TABLE "messages" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "text" text, "created_at" datetime, "updated_at" datetime);

but when i call Message.new on the console, the resulting object has an id of nil

>> a = Message.new
=> #<Message id: nil, text: nil, created_at: nil, updated_at: nil>

shouldn't the id come back populated?

+2  A: 

As far as I know, the id field only gets assigned on saves, not on news.

theIV
+2  A: 

No, that's the correct behavior. When you create an object via "new" (as in your example), Rails doesn't persist it to the database (just in memory).

If you do Message.create, or 'save' like theIV said, then the id will be populated.

fig