Create and Read
Learn to perform the create and read operations on Rails models.
Create
In the previous lesson, you created a model named Pet
and used the create_table
method to create the pets
table for this model with attributes name and age. Active Record provides you with two methods to set values for these attributes. These commands will be executed inside the rails console for now. In later lessons, you will learn to make updates to the database using web forms.
You can enter the rails console by using the command:
rails c
new
The first method is by using the new
command. This command instantiates a new object without saving it into the database. You can set the values for each attribute in separate commands.
Press + to interact
pet = Pet.newpet.name = "max"pet.age = "1"pet.save
- Line 1: Instantiates a new
Pet
record calledpet
. All attributes forpet
are initialized tonil
(unless a default value is specified for an attribute). - Line 2-3: Sets the values for
name
to “max”, andage
to “1” for the newly createdpet
. - Line 4:
new
only instantiates a