...

/

Create and Read

Create and Read

Learn to perform the create and read operations on Rails models.

We'll cover the following...

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.new
pet.name = "max"
pet.age = "1"
pet.save
  • Line 1: Instantiates a new Pet record called pet. All attributes for pet are initialized to nil (unless a default value is specified for an attribute).
  • Line 2-3: Sets the values for name to “max”, and age to “1” for the newly created pet.
  • Line 4: new only instantiates a
...