Kir
Kir

Reputation: 8111

get posts of followed users with acts_as_follower

I have 2 models in my Rails 3 app

User:

class User < ActiveRecord::Base

  acts_as_followable
  acts_as_follower

  has_many :posts

end

Post:

class Post < ActiveRecord::Base
  belongs_to :user
end

So, I can fetch users that I follow: User.find(1).following_users

But how to fetch posts of followed users? Something like User.find(1).following_users.posts

Upvotes: 0

Views: 612

Answers (2)

Gaurav Mukherjee
Gaurav Mukherjee

Reputation: 6335

User.following_users.collect{|u| u.posts}

This should work

Upvotes: 0

tomcocca
tomcocca

Reputation: 355

User.find(1).following_users just returns and arel reference, see here:

https://github.com/tcocca/acts_as_follower/blob/master/lib/acts_as_follower/follower.rb#L59

So,

User.find(1).following_users.includes(:posts)

should include the posts for the users in the query, but this will return an array of users. The following should work, loop through the users that are returned and collect their posts into an array

posts = User.find(1).following_users.includes(:posts).collect{|u| u.posts}.flatten

Upvotes: 2

Related Questions