0

I'm having trouble with the first loop. The second one successfully fills the @res[] array whereas the first one doesn't.

@res = {}
[:disc, :wpmot, :df, :ptsi, :eq].each do |t|
   tool = Tool.find_by(name: t)
   p (to - from)
   @res[t] = tool.certifieds.where(date: to - from)
end
.
.
.
@res = {}
[:disc, :wpmot, :df, :ptsi, :eq].each do |t|
   tool = Tool.find_by(name: t)
   p (Date.today - 1.months..Date.today)
   @res[t] = tool.certifieds.where(date: Date.today - 1.months..Date.today)
end

to and from are defined as such:

from = Date.new(start_year, start_month, start_day)
to = Date.new(end_year, end_month, end_day)

I then printed both values to see if they correspond but they didn't. p (Date.today - 1.months..Date.today) gave me 'Mon, 11 Nov 2019..Wed, 11 Dec 2019' whereas p (to - from) gave me '(1/1)'(sort of ratio between both dates). So I do understand that the first loop isn't working because the Date objects aren't correct. What is it that I'm doing wrong ?

Cheers.

HCKRMVT
  • 355
  • 3
  • 10
  • `1.month.ago..Date.today` or use `where(Tool.arel_table[:published_date].gte(1.month.ago))`. – max Dec 11 '19 at 14:32
  • Not directly related to your question but this seems like a lot of Ruby logic that should be database logic instead. You're doing 10 queries where you could do one. Something like `Certified.joins(:tools).where(date: from..to, certifieds: {name: %w[disc wpmot df ptsi eq]})`. – Jordan Running Dec 11 '19 at 16:41

1 Answers1

2

In the first loop you used to - from and it results in number of days between those two dates.

If I understood you correctly you want to find all the certifieds between dates so instead of substracting them supply a Range as a argument to where. You did it in the second loop with Date.today - 1.months..Date.today.

You can build range between two dates using .. syntax. Your where clause should look like this: .where(date: from..to)

P. Boro
  • 716
  • 3
  • 12
  • Thanks, this does solve my problem. I found [this](https://stackoverflow.com/a/18387395/10648704) post that provides an example. – HCKRMVT Dec 11 '19 at 14:47