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?
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?
On Mon, Feb 21, 2011 at 2:48 PM, Paul B.
[email protected]wrote:
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs