那么,我在处理...方面遇到了困难。
Preloading instance dependent scopes are not supported.
我有三个模型
class P < ApplicationRecord
has_many :as
has_many :cs
end
class C < ApplicationRecord
belongs_to :p
end
class A < ApplicationRecord
belongs_to :p
has_one :c, -> (a) { where(feature: a.feature) }, through: :p, source: :cs
end
我有三个快速的jsonapi序列化器
class PSerializer
include FastJsonapi::ObjectSerializer
has_many :as
end
class CSerializer
include FastJsonapi::ObjectSerializer
belongs_to :p
end
class ASerializer
include FastJsonapi::ObjectSerializer
belongs_to :p
has_one :c
end
而这个种子文件
p_model = P.create(title: 'PTitle')
4.times do |i|
A.create(title: "aTitle-#{i}", feature: "feature-#{i}", p: p_model)
C.create(title: "cTitle-#{i}", feature: "feature-#{i}", p: p_model)
end
我希望能够使用A及其C的P,但当我尝试这样做时。
PSerializer.new(P.first, { include: [:as, :'as.c'] }).serialized_json
我得到了
P Load (0.1ms) SELECT "ps".* FROM "ps" ORDER BY "ps"."id" ASC LIMIT ? [["LIMIT", 1]]
(0.1ms) SELECT "as"."id" FROM "as" WHERE "as"."p_id" = ? [["p_id", 1]]
A Load (0.1ms) SELECT "as".* FROM "as" WHERE "as"."p_id" = ? [["p_id", 1]]
C Load (0.2ms) SELECT "cs".* FROM "cs" INNER JOIN "ps" ON "cs"."p_id" = "ps"."id" WHERE "ps"."id" = ? AND "cs"."feature" = ? LIMIT ? [["id", 1], ["feature", "feature-0"], ["LIMIT", 1]]
C Load (0.1ms) SELECT "cs".* FROM "cs" INNER JOIN "ps" ON "cs"."p_id" = "ps"."id" WHERE "ps"."id" = ? AND "cs"."feature" = ? LIMIT ? [["id", 1], ["feature", "feature-1"], ["LIMIT", 1]]
C Load (0.1ms) SELECT "cs".* FROM "cs" INNER JOIN "ps" ON "cs"."p_id" = "ps"."id" WHERE "ps"."id" = ? AND "cs"."feature" = ? LIMIT ? [["id", 1], ["feature", "feature-2"], ["LIMIT", 1]]
C Load (0.1ms) SELECT "cs".* FROM "cs" INNER JOIN "ps" ON "cs"."p_id" = "ps"."id" WHERE "ps"."id" = ? AND "cs"."feature" = ? LIMIT ? [["id", 1], ["feature", "feature-3"], ["LIMIT", 1]]
看起来是 N + 1 的情况。但我知道可以使用includes解决它。
PSerializer.new(P.includes({ as: :c }).first, { include: [:as, :'as.c'] }).serialized_json
抱歉:
irb(main):010:0> PSerializer.new(P.includes({ as: :c }).first, { include: [:as, :'as.c'] }).serialized_json
P Load (0.1ms) SELECT "ps".* FROM "ps" ORDER BY "ps"."id" ASC LIMIT ? [["LIMIT", 1]]
A Load (0.1ms) SELECT "as".* FROM "as" WHERE "as"."p_id" = ? [["p_id", 1]]
Traceback (most recent call last):
1: from (irb):10
ArgumentError (The association scope 'c' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported.)
我可以尝试使用left_joins
irb(main):011:0> PSerializer.new(P.left_joins({ as: :c }).first, { include: [:as, :'as.c'] }).serialized_json
Traceback (most recent call last):
1: from (irb):11
ArgumentError (The association scope 'c' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported.)
实际上是同样的问题。 我该如何解决这个 N + 1 的问题?
我创建了一个包含这些模型的Rails仓库,所以您可以自己尝试。 https://github.com/X1ting/reproduce_preload_bug Rails版本为5.2.3 Ruby版本为2.5.1