Create Model Objects and Save to Database

❮❮ ❮ Back
Next ❯ ❯❯

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.

Task

Steps: Create New Object Using create

Launch Rails console:

rails console

Create new Person object and save to database via create:

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

Exit Rails console:

exit

Inspect people table:

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

Steps: Create New Object Using new/save

Launch Rails console:

rails console

Create new (unsaved) Person object via new:

marge = Person.new

Set object’s attribute values:

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

Save object to database:

marge.save

Exit Rails console:

exit

Inspect people table:

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

❮❮ ❮ Back
Next ❯ ❯❯