DEV Community

David Chedrick
David Chedrick

Posted on

Ruby: Using active record to update database in terminal

To start off I am assuming you are working in a Ruby project, using Active Record, and have a database up and running.
I am using SQLite for this.

If you are not using Active Record let me tell you that Active Record is a fantastic tool to handle your database. It can be done right in your terminal without any SQL statements. Plus, Active Record is a Ruby gem so all you need is include it in your Gemfile or use

gem install activerecord
Enter fullscreen mode Exit fullscreen mode

Check out the Active Record Documents
To learn how to connect to your database and how to create your tables.

Todays focus is updating your database with Active Record.

To start off I already have 3 users in my database:

code

We see the user jacque has a password column that is NULL, so lets give them a password.

I like to use a Rakefile to Pry.start my console.

Once the pry is running in the terminal I use User.last to view the user jacque.

code

Now lets give the user a new password. I will give them the password "cutiecat1"

In the terminal:

user = User.last
user.password = "cutiecat1"
user.save
Enter fullscreen mode Exit fullscreen mode

code

Lets double check our work.
Refresh the database and see our update!

code

Now, lets go ahead and add a new user named Bob.

In the terminal:

User.create(username: "Bob", password: "pass1234")
Enter fullscreen mode Exit fullscreen mode

code

Looks like it worked! Lets check with typing in the terminal:

 User.last
Enter fullscreen mode Exit fullscreen mode

code

Looks good in the terminal, now lets refresh and check our database.

code

Now what if Bob wants to be called "Bobby".
Back in the terminal we write:

bob = User.last
bob.update(:username => "Bobby")
Enter fullscreen mode Exit fullscreen mode

code

Again, lets double check the terminal this time we will just use our variable name:

bob
Enter fullscreen mode Exit fullscreen mode

code

And refresh the database:

code

Looks good, the database is updated.

Did you notice that I updated Bob's username slightly different that how I updated jacque's password?

Lets update Bob's name one more time to "Rob", but with the first syntax.
In the terminal:

bob.username = "Rob"
Enter fullscreen mode Exit fullscreen mode

code

Looks like the terminal is showing the name Rob now. But lets check the database

code

Still showing "Bobby" not "Rob".
But we can fix that with using .save
Back in the terminal:

bob.save
Enter fullscreen mode Exit fullscreen mode

code

Now lets check the database:

code

Perfect! Our database is updated.

Lets review those two ways to update.

bob.update(:username => "Bobby")

or

bob.username = "Rob"
bob.save

Now lets delete Bob with .destroy
In the terminal:

bob.destroy
Enter fullscreen mode Exit fullscreen mode

code

And Bob is now gone:

code

Top comments (0)