I have a setup with Members, Teams and Memberships.
Teams can have_many Memberships Teams can have_many Members through Memberships
Memberships belongs to a status
Only the latest Membership of a Member is valid.
I use this setup to keep a sort of audit log of a Member's history so I can see which teams he applied to, where he was kicked from and which he joined in. The Memberships table is timestamped and most of the distinction is done based on the created_at column.
Memberships has the following columns: id team_id member_id membership_status_id created_at updated_at
Now I would like a list for all team with their pending memberships. (defined by the membership_status_id)
I run this query: Membership.find(:all, :conditions => {:membership_status_id => PENDING})
This returns a list of all Memberships that HAVE EVER BEEN PENDING. So this also yields records that are long accepted or declined. Not really useful!
To be more precise, I want for all members their latest membership to match the PENDING condition.
Back to the drawing board, I designed the next query: Membership.find(:all, :group => 'member_id', :order => 'created_at DESC')
Now this actually groups correctly on the member ID and only gives me back 1 membership for each member. But it will give me the FIRST one. The order clause is completely ignored. How do I get the LAST one with a group_by part? My SQL is kind of rusty in that department.