It is possible to interact with the database of a Ruby on Rails project from the console. To enter the console execute this command from the command line within your project:
In our examples below we will be using the following databases. The relationship is that a
user has many
Viewing a record
To view the first user:
To view the 3rd user:
To find the pet with the name “Buttons”:
Using the where command:
In order to manipulate the data in the database it’s best to use variables. They are easy to use and very helpful.
To assign the first user to variable a and then display the contents of a:
To change the username for a:
To save the new changes to the database:
If the result says ‘true’ it means the data was saved to the database. If it comes back ‘false’ it means there’s a problem and the data wasn’t saved. The validations rules still apply that are in the model. Also if you have before save filters in the model that may cause the save to fail.
Create a new record
There are two ways to create a new record. Using the ‘save’ option or ‘create’ option.
Using the save method:
Using the create method: