简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM