Create model objects and save them to the database

❮ Back Next ❯

In this step, you will learn how to write Ruby code for creating new model objects and saving them to the database.

The Rails console is an interactive tool for running Ruby code that is able to access our app’s model code (among other things). We will use it to explore the kinds of things we can do with our model in Ruby on Rails. The Ruby code we will write in the console is the same sort of code we might write, for example, in our app’s controller methods to enable our app to perform various functions.

In the terminal, launch the Rails interactive console:

rails console

Note that the terminal has been taken over, and we are now inside the Rails console. A key indicator of this is that the terminal prompt has changed to something like 3.1.2 :001 >. We are now able to enter Ruby code into the terminal and run it. Entering exit into the Rails console will cause it to terminate and return us to the UNIX shell prompt (but don’t do this yet).

In the Rails console, enter this command for creating a new Person object:

Person.create(first_name: 'Homer', last_name: 'Simpson', height_inches: 60, weight_lbs: 241)

Note that the output of this command shows that a SQL INSERT command was run (INSERT INTO "people" ...), which indicates that a new row was inserted into the people database table.

Exit out of the Rails console to get back to the UNIX prompt:

exit

In the terminal, run this PostgreSQL command to confirm that the new row was added to the table people:

psql --command="SELECT * FROM people" practice_app_development

Note that the people table now contains one row with the “Homer” data.

The create command is not the only way to create and save model objects to the database; here is another way.

In the terminal, launch the Rails interactive console:

rails console

In the Rails console, enter this Ruby code to create a new “empty” Person object whose attributes have not been given values and who has not been saved to the database.

marge = Person.new

Note that a Person object is returned (looking similar to #<Person:0x000000010702cf08); however, no SQL commands are mentioned as having been run.

Set values for the marge object’s attributes:

marge.first_name = "Marge"
marge.last_name = "Simpson"
marge.height_inches = 102
marge.weight_lbs = 139

Note that still nothing has been saved to the database.

Save the marge object to the database:

marge.save

Note that the “Marge” object was now saved to the people database as indicated by SQL INSERT command (INSERT INTO "people" ...) mentioned in the output.

Exit out of the Rails console to get back to the UNIX prompt:

exit

In the terminal, run this PostgreSQL command to confirm that the new row was added to the table people:

psql --command="SELECT * FROM people" practice_app_development

Note that the people table now contains two rows, one with the “Homer” data and one with the “Marge” data.


❮ Back Next ❯