Topic: Association Extensions

One of my favorite things about ActiveRecord are association extensions. I have had numerous projects that I've worked on where I am wanting to fetch information based off of time periods that may or may not be changing.

The following code comes from a web app that is used to house event information for Resident Assistants on the campus I work at. I'm typically only interested for programs occuring in the present semester.

The following code is in the User model (user.rb)

has_many  :programs,
          :through  => :plans do
  def between(start_date = nil, end_date = nil)
    date_format = "%Y-%m-%d %H:%I:%S"
    date_for_where_clause = []
    if start_date
      date_for_where_clause << %(programs.start_date >= '#{start_date.strftime(date_format)}')
    if end_date
      date_for_where_clause << %(programs.start_date <= '#{end_date.strftime(date_format)}')
    where_clause = date_for_where_clause.join ' AND '
    find  :all,
          :conditions => where_clause

What this lovely piece of code does is allow me to pass date information to fetch only the programs I want, if that information is provided. So here is a usage example:

@all_programs = user.programs # => Returns all programs
@month_programs = user.programs.between(,1.month.from_now) # => Returns programs between today and one month from today

It's nice to be able to write code the is readible by a non-programmer and have them understand it. I showed my wife, who is not a programmer at all and asked her what she thought I was returning with that method and she nailed it. Something that would never have happened had I shown her the actual SQL.

You may only care about programs after a certain date, so you could just use the first part of the between method and have something like this:

@programs_after_today = user.programs.between( # => Returns programs after today

Hope this inspires you/helps you in trimming down your code.

If you see something that doesn't look right just let me know and I can try to fix it.

Last edited by Reedy (2006-06-21 13:58:19)

Most code examples are usually pulled out of the air and not tested. Use at your own risk!

Re: Association Extensions

Very nice.  I did not know you could add methods like that.