Chewy Gem - Query to get ranges of dates containing specific date

1.1k views Asked by At

I am using ElasticSearch with chewy GEM on a Rails application. I would some help in order to translate that:

all.select { |task|
 (task.start_at.to_date..task.end_at.to_date).cover?(Date.today)
}

to use a filter with chewy. I tried making this work by long hours, no success.

Any kind of help will be great.

Thanks

2

There are 2 answers

2
0e1val On

This code iterates over the collection "all". For each item it checks and returns true if the today is within the execution time scope of the task(it today's date is between the begin_at and end_at range), i.e if the task should be executed.

0
Mauricio Moraes On

I know its been a long time, but I'm working with the Chewy gem right now, so here it goes:

Assuming you have a TasksIndex with start_at and end_at fields well defined as of date type and with correct format:

field :start_at, type: 'date', format: 'basic_date_time_no_millis' # example, you can use other formats
field :end_at, type: 'date', format: 'basic_date_time_no_millis'

Then your filter can be like this:

def tasks_including_date(target_date)
  formatted_target_date = target_date.strftime('%Y-%m-%d')
  TasksIndex.filter{start_at <= formatted_target_date}.filter{end_at >= formatted_target_date}
end

Then you can just:

tasks_including_date(Date.today)

If you want the results itself, instead of the just the filtered scope, just use a to_ary on the result. It will handle you an aray with the results.