Create and Read
Explore how to create and read records in Ruby on Rails using Active Record methods such as new, create, find, find_by, first, and select. Understand how to add entries to your database with the rails console and seed files, retrieve single or multiple objects, and query specific record attributes effectively.
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.
- Line 1: Instantiates a new
Petrecord calledpet. All attributes forpetare initialized tonil(unless a default value is specified for an attribute). - Line 2-3: Sets the values for
nameto “max”, andageto “1” for the newly createdpet. - Line 4:
newonly