Topic: How do I find the largest value for attribute among several model?

Hi, everyone: I am also open to just straight-up refactoring what I'm finding to be pretty repetitive, but to give a baseline of how it's working....

I have for every contact a Campaign, which has_many of three types of Models: Email, Call, and Letter.

When an Email (Call or Letter) has been executed for a specific contact, I have a Contact_Email(_or_Call_or_Letter) which belongs to both the Contact and the Model (Email_or_Call_or_Letter).

Each Contact_Email for example pairing has a :date_sent attribute. So does each Contact_Call and Contact_Letter.

How do I find the latest of all of them?

Here is the code I wrote that can find the latest Email and my finding retyping similar code for Call and Letter, but then stuck on how to do a .max on all of them:

  def last_email(contact)
    #get campaign the contact belongs to
    @campaign = Campaign.find_by_id(contact.campaign_id)

    @last_email = ContactEmail.find(:last, 
                        :conditions => "contact_id = #{contact.id}",
                        :order => "date_sent DESC")

    @last_call = ContactCall.find(:last, 
                        :conditions => "contact_id = #{contact.id}",
                        :order => "date_sent DESC")

    @last_letter = ContactLetter.find(:last, 
                        :conditions => "contact_id = #{contact.id}",
                        :order => "date_sent DESC")

    # how do I get the latest of all of these to display?

    @email_template = Email.find_by_id(@last_email.email_id)

    if @last_email.nil?
      return "no email sent"
    else
      return @last_email.date_sent.to_s(:long) + link_to('email was sent', @email_template)
    end
  end

Re: How do I find the largest value for attribute among several model?

last_event = [@last_email, @last_call, @last_letter].sort_by(&:date_sent).last

Re: How do I find the largest value for attribute among several model?

nice will check it out....of course...now thinking if I need to move email, call, and letter into single table inheritance...boo hoo

Re: How do I find the largest value for attribute among several model?

I get an error because sometimes one of those instances is empty (when something hasn't been sent yet):

    last_event = [@last_email, @last_call, @last_letter].sort_by(&:date_sent).last

undefined method `date_sent' for nil:NilClass