user984621
user984621

Reputation: 48483

How to print my posts and posts of my friends?

I have 2 models, user and friendship, here's how they looks like:

class User < ActiveRecord::Base
  has_many :posts
  has_many :friendships, :conditions => { :confirmed => true }
  has_many :friend_requests, :class_name => 'Friendship', :conditions => { :confirmed => false }
  has_many :friends, :through => :friendships
  has_many :friends_friendships, :through => :friends, :source => :friendships
  has_many :friends_of_friends, :through => :friends_friendships, :source => :friend
  has_many :friends_listings, :through => :friends, :source => :listings
  has_many :friends_posts, :through => :friends, :source => :posts
  ...
end

and

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
  attr_accessible :friend_id
  ...
end

and here's how I fetch posts of currently logged in user and posts of his/her friends:

  @my_posts = current_user.posts.includes(:user)
  @friends_posts = current_user.friends_posts.includes(:user)

This is working well, but how can I load my posts + posts of my friends into one variable and display them as on Facebook? In other words, how can I merge those 2 queries into only one?

Thanks

Upvotes: 1

Views: 573

Answers (1)

rmagnum2002
rmagnum2002

Reputation: 11421

something like this:

ids = current_user.friends.pluck(:id) << current_user.id
posts = Post.where(user_id: ids)

return

SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1, 2, 3, 6)

then in view:

posts.each do |post|
  ....
end

Upvotes: 3

Related Questions