A PostgreSQL/Activerecord question!!
I’m trying to get all contacts for whom their most recent email has a direction of “incoming”. It seems simple but I can’t seem to figure it out yet! Any help would be appreciated.
Contacts have many Emails, Emails belong to a Contact. Emails have an attribute (direction) that say whether they are “incoming” or “outgoing” messages.
So far the closest I’ve gotten is something like this…
Contact.joins(emails).select( max(emails.created_at) as newest_email )
But i have no way of knowing whether that newest_email’s direction.
I need something that’s basically like this (i know this is not correct code, but this is where my thinking is at):
Contact.joins(emails).select( max(emails.created_at) as newest_email).where(newest_email.direction == “incoming”)
Let me know if I’m approaching this all wrong…