Searching with Ransack in Ruby on Rails

Sometimes we need or we want to develop a module quickly and easily that includes filters, sorting, pagination and we don’t want to spend so much time on it, that’s why there are already some implemented and tested tools that we can use and we can save us some headaches and time to achieve the same result or even better.

In this post, I will show you how to create a simple module in which it is possible to search books by different types of fields using Ruby on Rails, Bootstrap, Will paginate, Faker, and Ransack.

So, let’s get started, first we are going to create a new Rails application from the console with the following command:

rails new search-books-with-ransack --database=postgresql

This creates a directory called “search-books-with-ransack” which has an app that is called in the same way. So, first of all, we need to enter to that directory.

cd search-books-with-ransack

I like to use PostgreSQL for my default database because I usually deploy my apps in Heroku and it’s better for production apps.

Scaffolding

For this example, we can use scaffolding to create our books model running the following command in our console

additionally, run rails db:seed to populate the example data in the database

Run local server

So far, we can start our server with rails server or rails s and open our favorite web browser and if you go to the URL http://localhost:3000/books. You will see that we already have some books in our database.

So, that’s great but we still have a lot to do, so let’s do it

Let’s continue adding a simple enum for the genres in our book model and use it later in our filters with a dropdown

Bootstrap 4

I would like to add some styles with Bootstrap 4, and to be able to use it we must import it into our app/assets/stylesheets/application.scss file like the code listed below.

Make sure the file has .scss extension (or .sass for Sass syntax). If you have just generated a new Rails app, it may come with a .css file instead. If this file exists, it will be served instead of Sass, so rename it:

You can also check that the URL changes by adding the selected order, so if you share the link with a partner, in an email or external website, you can get the same result with the order and filters selected.

Pagination

So far so good, and now we can add the pagination gem, but since we are using Bootstrap 4, we will use will_paginate-bootstrap4 that already offers Bootstrap styles for pagination.

Let’s update the next line by adding the pagination in our index method

@books = @q.result

And we replace it with the following code

@books = @q.result.page(params[:page])

And finally, in our view, we will add the pagination code at the end of our list to be able to change the page