Alex
Alex

Reputation: 11157

models relationship question

i have a model Post and a model User where a post belongs to a User and a User has many posts . I would like to have me returned my friends posts .

After "grabbing" my friends with @friends = current_user.friends , i have to browse through all my @friends ( who of course are also User-s ) and have them return a array in a variable that contains the most recent 20 of my friends posts and i don't know how.

Upvotes: 0

Views: 33

Answers (1)

Amokrane Chentir
Amokrane Chentir

Reputation: 30405

In order to sort you can do:

array_posts = {}
@friends.each do |friend|
  array_posts[friend.name] = friend.posts.sort_by(&:created_at)
end

array_post will have for each of your friends their lists of posts sorted by their created_at attribute.

Upvotes: 1

Related Questions