避免对包含的 table 的 Actiontext::RichText 进行 N+1 查询

Avoiding N+1 Queries on Actiontext::RichText of an included table

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

无论如何,我正在尝试查询 returns 所有聊天记录。该查询看起来像这样:

Chat.all.includes(:messages)

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

scope :"with_rich_text_#{name}", -> { includes("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)