You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails中Txrow.create触发未预期N+1查询的原因排查问询

Ruby on Rails中Txrow.create触发未预期N+1查询的原因排查问询

问题背景

我现在碰到了一个很费解的问题:调用create_txrow方法创建Txrow记录时,明明传入的参数都是整数(控制台输出已经验证过类型),但Rails却自动发起了对Parti和NationVat的数据库查询,而且唯独没有触发PayingConsumer的查询,这完全不是我预期的行为。

下面是相关的代码、控制台输出和日志信息:

核心代码片段

# 仅处理整数参数的方法
def create_txrow( parti_id, paying_consumer_id, nation_vat_id )
  puts nation_vat_id
  puts nation_vat_id.class
  puts parti_id
  puts parti_id.class
  new_row = Txrow.create( 
    nation_vat_id: nation_vat_id,
    paying_consumer_id: paying_consumer_id,
    parti_id: parti_id,
    [...] # 其他属性
  )
end

控制台参数验证输出

1
Integer
2
Integer

日志中出现的未预期查询

NationVat Load (0.5ms) SELECT "nation_vats".* FROM "nation_vats" WHERE "nation_vats"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/concerns/taxation_methods.rb:253:in `create_txrow'
Parti Load (0.6ms) SELECT "partis".* FROM "partis" WHERE "partis"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/controllers/concerns/taxation_methods.rb:253:in `create_txrow'

注:第253行就是new_row = Txrow.create(...)这一行,我的代码里完全没有主动发起这些查询的逻辑。

额外上下文

为了避免N+1问题,我在初始化集合的时候已经用了.includes(:parti, :shopvat)做预加载,之后在集合内做筛选:

shopvat_for_item = shopvats.select{ |i| i.id = item.shopvat_id }.first
new_txrow = create_txrow( item.parti_id, item.cover.consumer_id, shopvat_for_item.nation_vat_id)

我的疑问

明明传入的是纯整数ID,Rails为什么要去查询对应的关联模型?而且为什么只有Parti和NationVat触发了查询,PayingConsumer却没有?有没有人遇到过类似的情况,或者能帮我分析下可能的原因?


内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:08:03