Try this:
person_hash = OrderState.maximum(:created_at, :group => :person_id)
person_hash.each |person_id, created_at|
state = OrderState.find_by_person_id_and_created_at(person_id, created_at)
end
Refer to the ActiveRecord documentation for more details.
If you want to do most of the calculations in the DB, try this:
OrderState.find_by_sql("SELECT A.* FROM order_states A,
(SELECT person_id, MAX(BA.created_at) AS created_at
FROM order_states BA
GROUP BY BA.person_id
) AS B
WHERE A.person_id = B.person_id AND
A.created_at = B.created_at")
In both approaches you should index created_at
column. If you have millions of users this is not a good strategy. You should store the last state in the Person table.