检查一条记录是否存在于一个有很多的关联中

Check if a record is present in a has-many association

我有一个 rails-api 应用程序,用户可以在其中关注其他用户。

要检查一个用户是否已经关注另一个用户,我需要在属性中包含一个查询,因此,我总是遇到一个 N+1 查询问题。

这是我的代码:

Index 用户控制器中的操作:

def index
    @users = ::User.all.paginate(page: params[:page])
end

追随者将始终包含在 User 模型中的 default_scope

index.json.jbuilder:

json.partial! 'attributes', collection: @users, as: :user

_attributes.json.jbuilder:

json.extract! user, :id, :firstname, :lastname, :username, :follower_count

is_follower = user.follower.find_by(id: current_user.id).present? if current_user

json.following is_follower

结果:

  User Load (0.1ms)  SELECT "users".* FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" =   [["followed_id", 14]]
  Rendered v1/user/users/_attributes.json.jbuilder (1.3ms)
  User Load (0.1ms)  SELECT "users".* FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" =   [["followed_id", 9]]
  Rendered v1/user/users/_attributes.json.jbuilder (1.4ms)
  User Load (0.1ms)  SELECT "users".* FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" =   [["followed_id", 13]]

是否有一些解决方法,或者是否有可能在 SQL 查询中生成一个动态属性,如果用户关注另一个用户,则包含布尔值?

非常感谢您。

我的第一个想法是,当您获得这样的用户列表时,使用 .includes 方法预先加载关注者 @users = ::User.all.includes(:followers).paginate(page: params[:page])。但也许,我没有正确理解你的问题?让我知道这是否有效,或者我是否应该将我的回答集中在不同的主题上。谢谢!

编辑:以下评论的正确答案:

也许您可以尝试user.followers.include?(current_user)利用预加载的关注者协会。