Filtering with Two Parameters in Rails

I have written about filtering in Rails before, but I have not written about filtering with two parameters. Filtering data with multiple parameters can be tricky.

Let’s imagine we are building a travel app where we could search for trips by location and type. Before we start implementing that feature lets think about how we are going to execute that.

We will probably need a form with two drop-down menus — one for locations and one for types. We will probably need to send ids to the controller index action by which we will sort the results. We will also probably need to create a custom route with two parameters to be able to send a request to the backend. With this scheme in our mind let’s start building our app!

We will need three models — Trip, Location and Type. Trip belongs to Location and Type, Location and Type have many Trips. With these model relationships we can start implementing our filtering feature. In our Type and Locations drop-downs it is necessary to give the input fields the values of the Type and Location ids and assign them html ids so we can grab them with document.querySelector().

const typeId = document.querySelector("#types").value 
const locationId = document.querySelector("#locations").value

Once we got a hold of the drop-downs values we can use them to send a fetch request to our API


To be able to do that we have to create a custom route in our config/routes.rb

get '/trips/:location_id/:type_id', to: 'trips#index'

That lets us send the params hash with a type_id and an location_id to the Trips controller and find the trip we are looking for

class TripsController < ApplicationController    
def index
if !params[:type_id] && !params[:location_id]
trips = Trip.all
render json: trips.to_json(include: [:type, :location])
trips = Trip.where(location: params[:location_id], type: params[:type_id])
render json: trips.to_json(include: [:type, :location])

Since our custom route belongs to the index action in the Trips controller we have to check if the params hash has type_id and location_id to be able to render correct JSON.

And this is it! A little tricky but for the most part simple. I hope you enjoyed reading this and happy coding!

Full Stack Software Engineer