Search logic

If I have this table...

id created_at updated_at user_id value

...and you can add several posts per user, how do I find all latest posts for each user?

I think I'm on the right track. But I get the first post for each user, not the latest. This is what I use.

Model.all(:select => "*, max(id)", :group => :user_id)

How do get the latest?

I think Iā€™m on the right track. But I get the first post for each user,

not the latest. This is what I use.

Model.all(:select => ā€œ*, max(id)ā€, :group => :user_id)

How do get the latest?

In Rails 3 syntax, Post.where(:user_id => given_user_id).group(:user_id).order(:updated_at DESC).limit(number).group_by(:&user_id) First, group the results by user_id.

Then, order the updated_at or created_at in DESC order. Then, you can limit the results for each user by passing a number. Then, finally return a hash of all the results with keys as user_id for easier and better retrieval.