Lessons: 8Length: 1.1 hours

Next lesson playing in 5 seconds

Cancel
  • Overview
  • Transcript

2.3 Add a Visit Count

It would be very nice if we could keep track of the number of times we visit a specific bookmark. We'll implement a visit count in this lesson.

2.3 Add a Visit Count

In the previous lesson, we've implemented a visit mechanism with a slug that basically shorthands the entire URL. Now we want to have a counter of how many times we have visited that you URL. So the way we do that is by creating another migration file the same way as we did before with the slug. Let's pick up on that and instead of using add_slug, we'll add in visit_count_to_bookmarks. Let's add in the visit_count, which will be an integer. Do that and you'll have that migration right away, which we can confirm in the migrate folder. Let's see, at visit_count two bookmarks. There it is. Let's ensure that we have the default of 0. And also make sure that we have a not null value. That way when creating a new bookmark, the visit_count will be set to 0. Now let's go ahead and type in the rake db migrate command. And now we can go to our controller. Let's go to app > controllers > visit_controller. We're gonna go here and increment that value of visit_count each time this action is called. This is just as easy as typing in bookmark.increment, and we use the attribute. So it is going to be the visit_count. And then we call bookmark.save. At the end we'll have an updated bookmark with the visit_count incremented by 1. And then we redirect. Now let's see how this goes. Let's go to our application, and notice that we still don't have any reference to the visit count. Let's fix that right away by going to the bookmarks index template. And here we'll add one more table cell, which will represent the bookmarks visit_count. In line 7, I'll add in another table header called visit_count. And then just below the page, and you will see that we have visit count like so. If you click on the slug, so we will be redirected to the actual URL, let's do that. Okay, and once we go back you will see the incremented number. So that's great. We have now successfully implemented a way of tracking the number of clicks into a specific URL.

Back to the top