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:
rails console
In our examples below we will be using the following databases. The relationship is that a user
has many pets
.
id | username | password |
---|---|---|
1 | Alex | al23lk@#$AFfFj23rhf0a98eraljkwqer |
2 | Benny | 2llLKJ#3j3#KJ#L7ouOuoI# |
7 | Carlton | #LKJ#LkjJ9f9wf0j |
id | user_id | pet_name |
---|---|---|
1 | 2 | Scruffy |
2 | 2 | Buddy |
3 | 3 | Buttons |
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:
|
Using variables
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:
|
Comments