Queries

The Query class is where you can store any complex queries your application may require.

Query classes are located in the app/queries/decidim/<my_module> directory, and named: <my_resource>_query.rb.

A typical query class looks like this:

#frozen_string_literal: true

# app/queries/decidim/my_module/my_resource_query.rb
module Decidim
  module MyModule
    class MyResourceQuery < Decidim::Query
      def self.for(components, extra_params)
        new(components, extra_params).query
      end

      def initialize(components, options)
        @components = components
        @start_at = options.delete(:start_at)
        @end_at = options.delete(:end_at)
      end

      def query
        resources = Decidim::MyModule::MyResource.where(component: @components)
        resources = resources.where("created_at >= ?", @start_at) if @start_at.present?
        resources = resources.where("created_at <= ?", @end_at) if @end_at.present?
        # and you can add any other query you need
        resources
      end
    end
  end
end

Then you can use the query in your code:

 @resources = Decidim::MyModule::MyQuery.for(components, start_at: 1.month.ago, end_at: Time.current)

More information

  • Decidim::Query is an internalization of Rectify gem created by Andy Pike