【问题标题】:Avoiding N+1 Queries on Actiontext::RichText of an included table避免对包含表的 Actiontext::RichText 进行 N+1 查询
【发布时间】:2021-03-08 21:41:34
【问题描述】:

我的数据是这样设置的: 一个聊天 has_many 消息 一条消息 has_rich_text :detail_html

无论如何,我正在尝试执行一个返回所有聊天记录的查询。该查询看起来像这样:

Chat.all.includes(:messages)

但是,由于 ActionText,我注意到我仍然有一个有意义的 N+1 查询。我见过像 Message.all.with_rich_text_meal_details 这样的东西,但问题是我不是用 has_rich_text 查询表,而是查询相关表。有任何想法吗?谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby activerecord actiontext


    【解决方案1】:

    范围:“with_rich_text_#{name}”,-> {包括(“rich_text_#{name}”)}

    source code 开始,has_one rich_text_* 与添加的Model 之间存在隐含关系has_rich_text。在你的情况下,Message has_one rich_text_meal_details

    所以你可以尝试通过以下方式预先加载meal_details

    Chat.all.includes(messages: :rich_text_meal_details)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 2019-03-16
      相关资源
      最近更新 更多