Reputation: 2293
id = current_user.id
@given_gifts = User.find(id).following_users.includes(:given_gifts).collect{|u| u.given_gifts}.flatten
@received_gifts = User.find(id).following_users.includes(:received_gifts).collect{|u| u.received_gifts}.flatten
@gifts = @given_gifts.zip(@received_gifts).flatten.compact
I'm trying to retrieve the list of gifts received and given by all users that the current user follows. Is there a better way to do this? The results are all out of order and are showing some duplicates. I'm trying to do an efficient query that I can paginate.
In my User.rb
has_many :given_gifts, class_name: 'Gift', foreign_key: 'giver_id'
has_many :received_gifts, class_name: 'Gift', foreign_key: 'receiver_id'
acts_as_followable
acts_as_follower
In my Gift.rb
belongs_to :giver, class_name: 'User'
belongs_to :receiver, class_name: 'User'
For the following functionality, i'm using the acts_as_follower gem.
Upvotes: 0
Views: 57
Reputation: 4545
Try something like this:
following_user_ids = current_user.following_users.pluck(:id)
Gift.where("(giver_id IN ?) OR (receiver_id IN ?)",
following_user_ids, following_user_ids).order(:created_at)
Basically this gets the list of following_users ids, and then uses an OR query to get gifts that are given or received by any user in the list.
The performance of this query will depend on the underlying database and the number of records you're juggling. But for small #s of following users (<= 100) it will generally perform fine. Performance will degrade as the number of following_user_ids climbs.
Upvotes: 1