gpt4 book ai didi

ruby-on-rails - 外键约束确实会导致 N+1 查询但没有约束,预加载工作正常

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:23 25 4
gpt4 key购买 nike

我在 markets 表中添加了 base_currency_idbase_currency_id2 分别有和没有外键约束,

def change
create_table :currencies do |t|
t.string :code
t.timestamps
end

create_table :market2 do |t|
t.string :code
t.integer :base_currency_id
t.integer :base_currency_id2
t.foreign_key :currencies, column: :base_currency_id2
t.integer :quote_currency_id
t.timestamps
end
end

ActiveRecord::Migration.change

Market 模型定义了以下关联,

class Market < ApplicationRecord
belongs_to :base_currency, class_name: 'Currency', foreign_key: :base_currency_id
belongs_to :base_currency2, class_name: 'Currency', foreign_key: :base_currency_id2
end

我不明白为什么以下关联之一会导致 N+1 查询,即使在此处进行预加载时也是如此,

Market.includes(:base_currency).each { |x| puts x.base_currency.code }
# Market Load (0.6ms) SELECT "markets".* FROM "markets"
# Currency Load (0.3ms) SELECT "currencies".* FROM "currencies" WHERE "currencies"."id" = $1 [["id", 1]]
# INR
# INR


Market.includes(:base_currency2).each { |x| puts x.base_currency.code }
# Market Load (0.5ms) SELECT "markets".* FROM "markets"
# Currency Load (0.4ms) SELECT "currencies".* FROM "currencies" WHERE "currencies"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
# INR
# Currency Load (0.4ms) SELECT "currencies".* FROM "currencies" WHERE "currencies"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
# INR

如果我在这里遗漏了什么,请解释。

最佳答案

将 block 内调用的关联更改为字母中的基础货币 2。

Market.includes(:base_currency2).each { |x| puts x.base_currency2.code }

关于ruby-on-rails - 外键约束确实会导致 N+1 查询但没有约束,预加载工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57558475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com