检索用户关注的所有用户的帖子 - rails - ActiveRecord [英] Retrieving posts of all users that a user follows - rails - ActiveRecord

查看:60
本文介绍了检索用户关注的所有用户的帖子 - rails - ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 rails 应用程序,用户可以在其中互相赠送虚拟礼物.每个礼物都属于两个用户,送礼者和接受者.

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.

在我的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

在我的Gift.rb

belongs_to :giver, class_name: 'User'
belongs_to :receiver, class_name: 'User'

我正在使用 acts_as_follower gem 来允许用户关注其他用户并查看礼物列表他们关注的用户给予和接受.

I'm using the acts_as_follower gem to allow users to follow other users and see the list of gifts that the users they follow gave and received.

在我的控制器中:

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 sure I'm doing this really wrong. This gives me a list of gifts, with some duplicates, and they are all out of order. How can I efficiently grab the list of all gifts given and received by the users that any given user follows, so they there are no duplicates, they are all in order, and so that i can paginate the results?

如果作为用户,我正在关注用户 X 和用户 Y,并且用户 X 给了用户 Y 一份礼物,那么在我的供稿中,我只想看到一次提及此内容,而不是两次提及同一礼物.

If as a user, I am following user X and user Y, and user X gave user Y a gift, in my feed I only want to see one mention of this instead of two mentions of this same gift.

推荐答案

我会在我的礼物模型中创建一个自定义方法,试试这个:

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

...

这将最终生成并运行如下所示的 SQL 调用:

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))

假设 ID 为 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

这篇关于检索用户关注的所有用户的帖子 - rails - ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆