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
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:
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.
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
Lets double check our work.
Refresh the database and see our update!
Now, lets go ahead and add a new user named Bob.
In the terminal:
User.create(username: "Bob", password: "pass1234")
Looks like it worked! Lets check with typing in the terminal:
User.last
Looks good in the terminal, now lets refresh and check our database.
Now what if Bob wants to be called "Bobby".
Back in the terminal we write:
bob = User.last
bob.update(:username => "Bobby")
Again, lets double check the terminal this time we will just use our variable name:
bob
And refresh the database:
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"
Looks like the terminal is showing the name Rob now. But lets check the database
Still showing "Bobby" not "Rob".
But we can fix that with using .save
Back in the terminal:
bob.save
Now lets check the database:
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
And Bob is now gone:
Top comments (0)