Alex Smith
Alex Smith

Reputation: 191

Get Posts of accounts User is Following w/ acts_as_follower

I'm using acts_as_follower to allow users to follow each other within my application. I'm wondering how I can retrieve the posts of the users they follow? I currently have built a solution, but it doesn't show the posts in order that they were created and it can't be paginated with will_paginate. Suggestions? My code below is how I'm currently going about it in the pages controller to render the feed on the homepage.

@posts = current_user.following_users.includes(:posts).collect{|u| u.posts.paginate(:page => params[:page]).order("created_at DESC")}.flatten

Upvotes: 1

Views: 289

Answers (1)

AJcodez
AJcodez

Reputation: 34176

Not a sql expert, but try this:

following_ids = current_user.following_users.map(&:id)
Post.where(user_id: following_ids).order("created_at DESC").paginate(page: params[:page])

2 queries. You can certainly do it with one and joins, but I like the simplicity

Upvotes: 3

Related Questions