Retrieving posts of all users that a user follows - rails - ActiveRecord

前端 未结 2 1371
夕颜
夕颜 2021-01-24 13:54

I have a simple rails app where users can give virtual gifts to each other. Each gift belongs to two users, the giver and the receiver.

In my User.rb

相关标签:
2条回答
  • 2021-01-24 14:30

    Tested this on Rails 4 and associations(not the gem). This will give distinct gift records ordered by created_at :-

    @gifts = User.find(id).following_users.joins(:received_gifts, :given_gifts).select('DISTINCT gifts. *')

    Also as per the documentation, I think you should use followers_scoped instead of followers inorder to get an Arel scope instead of an array of elements

    0 讨论(0)
  • 2021-01-24 14:44

    I would create a custom method in my Gift model, try this:

    gift.rb

    class Gift < ActiveResource::Base
    
    ...
    
    def self.all_gifts(user_id)
      follower_ids = User.find(user_id).following_users.pluck(:id)
      Gift.where('giver_id in (?) OR receiver_id in (?)', follower_ids, follower_ids).uniq
    end
    
    ...
    

    This will end up generating and running a SQL call that looks like this:

    SELECT DISTINCT "gifts".* FROM "gifts" WHERE (giver_id in (1,2,3) OR receiver_id in (1,2,3))
    

    Given that users with IDs 1, 2, and 3 follow the user. You should be able to paginate these results like this in your controller:

    id = current_user.id
    Gift.all_gifts(id).paginate # any paginate attributes
    
    0 讨论(0)
提交回复
热议问题