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.

On Sat, Dec 15, 2007 at 11:58:36PM -0800, partydrone wrote:

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

On Sun, Dec 16, 2007 at 11:41:49AM -0800, partydrone wrote:

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.

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

On Sun, Dec 16, 2007 at 12:52:39PM -0800, partydrone wrote:

[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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs