I have a model called a Statement
that belongs to a Member
. Given an array of members, I want to create a query that will return the most recent statement for each of those members (preferably in one nice clean query).
I thought I might be able to achieve this using group
and order
- something like:
# @members is already in an array
@statements = Statement.all(
:conditions => ["member_id IN(?)", @members.collect{|m| m.id}],
:group => :member_id,
:order => "created_at DESC"
)
But unfortunately the above always returns the oldest statement for each member. I've tried swapping the order option round, but alas it always returns the oldest statement of the group rather than the most recent.
I'm guessing group_by
isn't the way to achieve this - so how do I achieve it?
PS - any non Ruby/Rails people reading this, if you know how to achieve this in raw MySQL, then fire away.