Kievbuy
7/20/2018 - 9:20 AM

Searching inside time ranges: Sunspot rails

I have courses which have date ranges (plannings) with relation has_many

# in the model 

class Course < ActiveRecord::Base
  has_many :planings
    
  searchable do
    time :course_dates, multiple: true do
      planings.map { |p| (p.start_at..p.finish_at).to_a }
    end
  end
    
end

# in the controller

def index
    @search = Course.search do
      if params[:start_at].present? && params[:finish_at].present?
        with(:course_dates, (params[:start_at]..params[:finish_at]))
      end
    end
    @courses = @search.results
  end
#Have almost the same problem, in my case start_date and end_date wasn't really a date, just a year (integer), solve it with multiple value fields as range:

searchable do
  date :course_date, multiple: true do
    plannings.map{|p| (p.start_date..p.end_date).to_a}
  end
  ...
end

#so course_date contain all years when courses going. If you have 2001-2003 and 2005-2007(2001, 2002, 2003, 2005, 2006, 2007) and search with equal_to.