DEV Community

Paulina Delmore
Paulina Delmore

Posted on


I've been working on my final project for a couple of weeks now, and I hit a few roadblocks in terms of the functionality that I know how to achieve vs the functionality that I want in my project that I thought I had no idea how to implement. One of them was table pagination. During a brief conversation with the instructor he assured me that it's something I should be able to do with the knowledge of basic Ruby and Rails that I have so far. And, as it turns out, he was right.

What I wanted to achieve:

  • split the records in the table into chunks (10 per page)
  • display those chunks on consecutive pages
  • links "previous page" and "next page" to navigate the records
  • first page has disabled "previous" link
  • last page has disabled "next" link

What I needed:
The instructor noted I probably needed to use params, as well as .limit and .offset methods. Since we haven't talked about the two methods in class, I had to read up on those first.

What I did:
First, I wrote my steps in a form of comments:

    # set notes_per_page number
    # set params (:page), default to 0
    # define pagination limit and offset - limit is notes_per_page, offset is notes_per_page * page params
    # get number of notes
    # get number of pages, convert to float
    # divide page_number by notes_per_page, round, to integer
    # get last page - rounded_page_number minus 1 because count starts at 0
Enter fullscreen mode Exit fullscreen mode

Second, I went comment by comment and wrote the code, one variable at a time. I was amazed at how easy it was to do it after explaining to myself what my code was supposed to achieve first.

Third, I had to figure out how to go about "previous" and "next" buttons. Again, I wrote myself the steps in a mix of Ruby and English:

    # if page param == 0, can't click on "previous", can click on "next"
    # if page param = last_page, can click on "previous", can't click on "next"
    # else can click on both
    # link takes to ?page=<%= page param +/- 1 %>
Enter fullscreen mode Exit fullscreen mode

I know there are much easier, faster and prettier ways of achieving what I just did. But what I've learned is that many features are really easy to create - all is needed is an understanding of what it is we are trying to do, and work one line at a time. That's what's amazing about programming.

And suddenly, the next feature that I wanted to add to my final project - messaging option between the users - doesn't seem as difficult to write as I thought it was!

Top comments (0)