views:

19

answers:

2

I'm going through Ruby on Rails Up and Running by O'Reilly and have run into a question that I'm not sure where to go to for help.

I'm at the part in the book where I'm creating new objects from the console and then saving them to the database. I've already created the database (MySQL), run the migration and finally verified that rails created the database schema (also have gone through the rest of the book to this point).

To create the object I ran the following commands:

ruby script/console

photo = Photo.new

The output that the book showed is:

#<Photo:0x35301d8 @attributes={"filename"=>""}, @new_record=true>

However, the output that I got was:

#<Photo id: nil, filename: nil>

From what I understand, when a new object is created in this manner a unique ID is generated to identify that object but it appears that in my case no unique id was generated. I've done quite a bit of googling on this and it's a difficult thing to search for because it's not an error message per-se; but I'm pretty sure something has gone wrong. So I thought I'd come to the stackoverflow community for help.

Thanks, Adam

A: 

If you're talking about the 0x35301d8 part: That unique id is always "generated" (actually it's the memory address of the object, so generated isn't the right word, but that doesn't matter). However ActiveRecord defines it's own inspect method which gives a bit more readable output and simply does not show the id.

You can still query the id by calling photo.object_id.

The reason that the id is displayed in the article is probably that the article uses an older version of rails, where ActiveRecord did not yet define this version of the inspect method.

The id: nil that's displayed in your version, is about a different id. That's the database id your ActiveRecord object has, and it won't be generated until you save your object to the db.

sepp2k
That makes perfect sense, thank you.
adammichaelc
+3  A: 

The (database) ID is only generated after saving to the database. The new method just instantiates the object, doesn't save it.

Be careful not to mistake the Ruby object's object_id (0x35301d8) for the database ID (generally a sequential integer). The database ID is the only one you really care about when writing Rails apps.

As for the difference in output, I'm going to hazard a guess that it's a difference in Rails (ActiveRecord) versions.

tfe