简体   繁体   中英

Searchkick aggregations for has_and_belongs_to_many

I have a Rails 5 app and I'm trying to do an aggregations search for a has_and_belongs_to_many association.

Here is the code that I have so far:

event.rb:

class Event < ApplicationRecord
  searchkick text_start: [:title]

  has_and_belongs_to_many :services
  has_and_belongs_to_many :sectors

  def search_data
    atributes.merge(
      title: title,
      description: description,
      sector_name: sectors.map(&:name),
      service_name: services.map(&:name)
    )
  end

end

events_controller.rb:

def index
  query = params[:j].presence || "*"
  conditions = {}
  conditions[:sector] = params[:sector] if params[:sector].present?
  conditions[:service] = params[:service] if params[:service].present?
  conditions[:date] = params[:date] if params[:date].present?
  @events = Event.search query, where: conditions, aggs: [:sector, :service, :date], order: {created_at: {order: "desc"}}, page: params[:page], per_page: 10
end

When I call Event.reindex in the console I was expecting to to show that the sectors and services had been indexed but it doesn't work.

To be honest I'm getting quite lost and going round in circles so any help would be much appreciated.

This is the code that ended up working for me:

event.rb:

def index
    query = params[:j].presence || "*"
    conditions = {start_date: {"gte": "now/d"}}
    conditions[:sector_name] = params[:sector_name] if params[:sector_name].present?
    conditions[:service_name] = params[:service_name] if params[:service_name].present?
    conditions[:start_date] = params[:start_date] if params[:start_date].present?
    @events = Event.search query, where: conditions, aggs: [:sector_name, :service_name], order: {start_date: {order: "asc", unmapped_type: "long"}}, page: params[:page], per_page: 10
end

events_controller.rb:

def search_data
  {
    title: title,
    location: location,
    description: description,
    start_date: start_date,
    sector_name: sectors.map(&:name),
    service_name: services.map(&:name)
  }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM