Ruby On Rails Lesson
Creating User Objects
We’ve done some good prep work, and now it’s time to cash in and learn about Active Record by playing with our newly created User model. As in Chapter 4, our tool of choice is the Rails console. Since we don’t (yet) want to make any changes to our database, we’ll start the console in a sandbox:
As indicated by the helpful message ‘‘Any modifications you make will be rolled back on exit,’’ when started in a sandbox the console will ‘‘roll back’’ (i.e., undo) any database changes introduced during the session.
In the consolesession in Section 4.4.5, we created a new user object with User.new, which we had access to only after requiring the example user file in Listing 4.9. With models, the situation is different; as you may recall from Section 4.4.4, the Rails console automatically loads the Rails environment, which includes the models. This means that we can make a new user object without any further work:
We see here the default console representation of a user object, which prints out the same attributes shown in Figure 6.2 and Listing 6.5.
When called with no arguments, User.new returns an object with all nil attributes. In Section 4.4.5, we designed the example User class to take an initialization hash to set the object attributes; that design choice was motivated by Active Record, which allows objects to be initialized in the same way:
Here we see that the name and email attributes have been set as expected. If you’ve been tailing the development log, you may have noticed that no new lines have shown up yet. This is because calling User.new doesn’t touch the database; it
simply creates a new Ruby object in memory. To save the user object to the database, we call the save method on the user variable:
The save method returns true if it succeeds and false otherwise. (Currently, all saves should succeed; we’ll see cases in Section 6.2 when some will fail.) As soon as you save, you should see a line in the development log with the SQL command to INSERT INTO "users". Because of the many methods supplied by Active Record, we won’t ever need raw SQL in this book, and I’ll omit discussion of the SQL commands from now on. But you can learn a lot by watching the log.