7

I'm trying to count all the records between 2 dates that are finished. This means that the created_at field is between start_date and end_date and the finished_at field is not null.

I can use the following expression to get the records that didn't finish:

Record.count(:all, :conditions => {:created_at => start_date..end_date, :finished_at => nil })

Is there a similar way to count the records where finished at is not nil?

dcarneiro
  • 7,060
  • 11
  • 51
  • 74
  • You may use some gems, such as Squeel, meta-where. See http://stackoverflow.com/questions/4252349/rail-3-where-condition-using-not-null – gayavat Mar 27 '12 at 10:50
  • @gayavat I don't think Squeel support a between functionality so I have to do Record.count{(created_at > start_date) & (created_at < end_date) & (finished_at != nil)} but it works. – dcarneiro Mar 27 '12 at 11:10

1 Answers1

9

This should work just fine unless I'm missing something.

Record.where(:created_at => start_date..end_date).where('finished_at IS NOT NULL').count
aNoble
  • 7,033
  • 2
  • 37
  • 33
  • I ended going with Record.where("created_at BETWEEN ? AND ? AND finished_at IS NOT NULL", start_date, end_date).count to keep both conditions together – dcarneiro Mar 28 '12 at 08:52