我有一個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" = $1 [["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" = $1 [["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" = $1 [["followed_id", 13]]
有一些解決辦法或者是它以某種方式可能在SQL查詢中生成一個動態屬性,其中包含布爾值,如果是用戶關注其他用戶?
非常感謝您提前。
我在我的用戶模型中有一個'default scope',它自動包含關注者。 – Tobias
我的錯誤。當我第一次讀它時,我一定錯過了那部分。看起來像在你的'jbuilder'的第2行中,你正在檢查當前用戶是否包含在追隨者列表中,但不確定'follower(user)'方法正在做什麼。也許你可以嘗試'user.followers.include?(current_user)'來使用預先加載的關注者關聯。 –
非常感謝! 「包括」方法解決了這個問題。 – Tobias