Some notes using Ransack gem

Tram Ho

Writing a short article like this is not too good to mention, but the two adjustments when searching with Ransack here are always discrete instructions on Stackoverflow so I wrote this article. I hope you share more of the case you have to edit when using Ransack gem so I can add more in the article.

Create a Rails project and prepare the steps

In this step run the rails new command, prepare the models and add the Ransack gem. Because I am also lazy, I would like to skip this step. However, I will upload the tables in the database that I will use in this article.

Then you do a form search with filters: search keywords, tags, number of comments. And we get to problem 1.

Problem 1: Search for tags separated by commas

The request you receive is in the tag search form, you can type multiple tags, each separated by a comma. The result returned must contain 1 of those tags.

The analysis here is that we use the relationship as OR. And we will have a way of affecting Ruby’s split() input.

So the code will be written as follows

And in the view you set

The search was satisfactory, but looking at the size of the index looked horrible. So I rewrote the code as follows

So it looks less scary, although it still seems not very neat

Problem 2: Search based on the number of comments

The next problem is to search and return results of posts that have more comments than a certain number. Now we will use the secondary query and Arel gem

With the Arel gem, we have to add the following:

Then, on the model, we add the following

And we have a property named comments_count . In ransack there is also _gteq to compare greater or equal (Greater or Equal). So we just need to combine it


Share the news now

Source : Viblo