Day 10: #100DaysofCode - ActiveRecord and a Database

sincerelybrittany profile image Brittany Updated on ・2 min read

Song of the day





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")


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

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

User.find_by(username: "Carla").update(username: 'Carly')

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

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.


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:


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

Post.where(content: "this is content").destroy_all

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

Posted on by:

sincerelybrittany profile



Developer | Software Engineer πŸ‘©πŸΎβ€πŸ’» | Determined | Music & Dance | Completed #100DaysofCode | #WomenWhoCode


markdown guide