Ruby on Rails Get Query Filter

Okechukwu Uneze
1 min readJun 10, 2022

Given a GET request is made to “/users?<some-query-here>”, then all users that meet the query criteria are returned in a JSON array, and the status code is 200.

first we will create our index action that renders users and set a before_action that calls filter_users before the index action is called.

class UsersController < ApplicationController
before_action :filter_users, only: %i[ index ]
# GET /users
def index
render json: @users, status: :ok
end
end

The next step is to write filter_users action. In our filter_users action we will check first if there is a query string using request.query_string.present?. If query string is present in the url parse it using CGI.parse(request.query_string) then return query from database using where, else return all users.

private# filters users based on query params
def filter_users
if request.query_string.present?
filter_params = CGI.parse(request.query_string)
@users = User.where(filter_params)
else
@users = User.all
end
end

Full Code

class UsersController < ApplicationController
before_action :filter_users, only: %i[ index ]
# GET /users
def index
render json: @users, status: :ok
end
private # filters users based on query params
def filter_users
if request.query_string.present?
filter_params = CGI.parse(request.query_string)
@users = User.where(filter_params)
else
@users = User.all
end
end
end

Happy Coding

--

--