views:

19

answers:

2

Company has_many Contacts

Company has_many ContactEmails :through => :contacts

ContactEmail belongs_to Contact

Contact belongs_to Company

Contact has_many ContactEmails

For a specific instance of Company, how can I find all ContactEmails and filter on an attribute, such as date_sent?

I tried Company.ContactEmails but I don't think it can make that association.

A: 

You probably want to use a named scope for this. This works for Rails 2.3, but wouldn't change much for Rails 3.

I haven't tested it, but something like this should work. The conditions may need to be tweaked for a proper date comparison.

ContactEmail < ActiveRecord::Base
  named_scope :by_date_sent, lambda {|d| { :conditions => ["date_sent = ?", d]}}
end

@company.contact_emails.by_date_sent(Date.today)
Beerlington
interesting...I don't know a has_one :through for Contactemails?
Angela
hmmm...you are right....I didn't use a lambda for named scope just use conditions....should I use it? wondering why searchlogic isn't allowing me to do the same thing....are you familiar with searchlogic?
Angela
I'm not too familiar with searchlogic, other than just reading the github README. It seems like it could work, but I didn't see any examples that dealt with dates. I did come across someone using it for this purpose though http://stackoverflow.com/questions/1829477/date-conditions-using-search-logic
Beerlington
A: 

At least 2 semantic of ways to do it:

  1. Through named_scope as Beerlington has suggested (The right way to do it).
  2. Just pass the conditions to the finders:
    company.contact_emails.all(:conditions => ["date_sent = ?", d])
Swanand