Active Queryable is a lightweight Ruby gem designed to simplify sorting, filtering, and paginating models in Rails applications. Its intuitive API and seamless integration with ActiveModel make building complex queries a breeze.
- Easy integration with Rails models.
- Support for dynamic sorting, filtering, and pagination.
- Compatible with JSON:API specification for pagination parameters.
- Extensible through custom scopes for advanced filtering needs.
Ensure you have Rails >= 5.2 (or specify another version if needed) and then add Active Queryable to your Gemfile:
gem'active_queryable'or alternatively bundle add active_queryable
First, include the as_queryable method in your model to enable the gem.
classPerson < ActiveModel::Base# Add this line to enable the gemas_queryableendThen, configure the order and filters you want to use:
classPerson < ActiveModel::Base# Add this line to enable the gemas_queryable# Configure order and filtersqueryableorder: {name: :asc},filter: [:name]endThis will allow you to query your model using the query_by method:
Person.query_by(order: '-name')# SELECT * FROM people ORDER BY name DESC LIMIT 25Person.query_by(filter: {name: 'john'})# SELECT * FROM people WHERE people.name = 'john' LIMIT 25You can also use pagination, using kaminari under the hood:
Person.query_by(per: 20,page: 2)# SELECT * FROM people LIMIT 20 OFFSET 20# Accepts also JSON:API-styled parametersPerson.query_by(page: {number: 2,size: 20})# SELECT * FROM people LIMIT 20 OFFSET 20You can also use custom scopes to extend the filtering and ordering capabilities.
The gem will look for a scope with the same name as the filter, and a method with the same name as the order.
classPerson < ActiveModel::Base# Add this line to enable the gemas_queryable# Configure order and filtersqueryableorder: {fullname: :asc},filter: [:name_like]# the `of_name_like` scope will be used when filtering by `name_like`scope:of_name_like,->(name){where('name LIKE ?',"%#{name}%")}# the `by_name` method will be used when ordering by `name`order:by_name,->(direction){order(firstname: direction,lastname: direction)}endactive_queryable is maintained by mònade srl.
We <3 open source software. Contact us for your next project!