Database Agnostic Date Functions

I have a model for events with a start date and an end date. I want to
find all events for the current month. How would I go about that,
exactly?

Thanks.

I have a model for events with a start date and an end date. I want to
find all events for the current month. How would I go about that,
exactly?

You could mean any one of three things: events starting in a particular
month, events ending in that month, or events entirely contained in a
particular month. I'm assuming you mean events starting in a particular
month; the conditions will be slightly different for the other options, and
those differences are left as an exercise for the reader (i.e. don't ask me
to write your code for you when I've shown you how to go about it).

class Event < ActiveRecord::Base

  def self.find_for_month(date = Date.today)
    find :all, :conditions => [ 'start_date BETWEEN ? AND ?',
                                *month_range(date) ]
  end

  # stuff...

  private

  def month_range(date = Date.today)
    first = date - (date.day - 1)
    last = first + 32
    last -= last.day
    [ first, last ]
  end

end

Thanks.

--Greg

Thanks for your response, Greg.

Here's what I tried doing:

class Event < ActiveRecord::Base

  def self.find_for_month(date = Date.today)
    find(:all, :conditions => ['start_date BETWEEN ? AND ? OR end_date
BETWEEN ? AND ?', *month_range(date)], :order => 'start_date ASC')
  end

This is wrong, first of all, because you are referring to four variables to
substitute in the conditions clause, but only providing two.

  private #--------------------

  def month_range(date = Date.today)
    first = date - (date.day - 1)
    last = first + 32
    last -= last.day
    [first, last] * 2
  end

end

When I test it in script/console, though, I get an error:

NoMethodError: undefined method `month_range' for Reservation:Class

[...]

This is wrong, and it's my fault. The find_for_month method is a class
method, whereas the month_range method is an instance method. That's why it
isn't being found.

--Greg

This is wrong, first of all, because you are referring to four variables to
substitute in the conditions clause, but only providing two.

I tried it and it seems to be working fine. I read in the Ruby docs
that:

[1, 2] * 2

returns:

[1, 2, 1, 2]

So using [first, last] * 2 actually returns four variables, not just
the two.

Thanks a TON for your help. Much appreciated.

Andy

> This is wrong, first of all, because you are referring to four variables to
> substitute in the conditions clause, but only providing two.

I tried it and it seems to be working fine. I read in the Ruby docs
that:

[1, 2] * 2

returns:

[1, 2, 1, 2]

So using [first, last] * 2 actually returns four variables, not just
the two.

Ah, sorry, I missed the *2.

Thanks a TON for your help. Much appreciated.

Sure.

Andy

--Greg