DEV Community

Brittany
Brittany

Posted on • Edited on

Day 10: #100DaysofCode - ActiveRecord and a Database

Song of the day

Create

Read

Update

Delete

We've already covered how to create and read(find) data within a database while using ActiveRecord.

Now, you will need to update and delete that data. Once again go into tux or rake console and lets use the data from my last post to update and delete(destroy) from our database.

a = User.create(username: username= "Ashley")
b = User.create(username: username= "Bob")
c = User.create(username: username= "Carla")

p = Post.create(title: title= "first title", content: content="this is content")
p2 = Post.create(title: title= "second title", content: content="this is content too")
p3 = Post.create(title: title= "third title", content: content="this is content")
Enter fullscreen mode Exit fullscreen mode

Update

user = User.find_by(username: 'Ashley')
=> #<User:0x00007f9ad6395080 id: 1, username: "Ash">
user.update(name: 'Ash')

Enter fullscreen mode Exit fullscreen mode

You can also link the methods on one line to update the database, like this:

User.find_by(username: "Carla").update(username: 'Carly')
Enter fullscreen mode Exit fullscreen mode

Or what if you wanted to update the first post to be updated and assigned to a particular user? You would update it by doing the following:

p2.user = a

Enter fullscreen mode Exit fullscreen mode

Yup, it is that simple, you have to set the user of the second post to a (Ashley) and now the post has a user. ActiveRecord makes it that simple to do.

Delete

For some reason, delete and destroy always make me nervous when dealing with databases. However, it is something we need to know how to do for storage reasons and because many times you will not need information anymore.

To delete a user from our simple example, we run one of the following:

User.find(2).destroy
User.destroy(2)
Enter fullscreen mode Exit fullscreen mode

You can also specify what you want to delete, for example:

Post.where(content: "this is content").destroy_all
Enter fullscreen mode Exit fullscreen mode

Now that we have covered the basics of CRUD using ActiveRecord we can move on to setting up our application and views.

Check out my #100DaysofCode Github Repo

Top comments (0)