How do I find the .max of an attribute value among a group of different Models?

Posted by Angela on Stack Overflow See other posts from Stack Overflow or by Angela
Published on 2010-05-15T23:43:34Z Indexed on 2010/05/15 23:50 UTC
Read the original article Hit count: 241

Filed under:
|
|

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?

    if @last_sent_email.nil?
      return "no email sent"
    else
      return @last_sent_email.date_sent
    end
  end

Question 1: With what I have, how can I find effectively @last_event given I can find the last Email, last Call, and last Letter for every contact?

Question 2: How can I remove the repetitive code that I have to write for each Model?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about max