Search code examples
ruby-on-railsrubyactiverecordactiontext

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


My data is set up like this: a Chat has_many messages a Message has_rich_text :detail_html

Anyhow, I am trying to do a query that returns all the Chats. That query looks something like this:

Chat.all.includes(:messages)

However, because of ActionText, I'm noticing that I still have an N+1 query which makes sense. I've seen stuff like Message.all.with_rich_text_meal_details which works but the issue is that I'm not query the table with the has_rich_text, instead I'm querying a related table. Any ideas? Thanks!


Solution

  • scope :"with_rich_text_#{name}", -> { includes("rich_text_#{name}") }

    From source code, there's an implicit relationship has_one rich_text_* with the Model added has_rich_text. In your case, Message has_one rich_text_meal_details.

    So you could try to eager loading meal_details by:

    Chat.all.includes(messages: :rich_text_meal_details)