How to correctly use includes to solve N+1 rails

54 Views Asked by At

I have 3 models:

1)ContentType (parent)

2)RecentTools (last 3 childs of ContentType, model is Tool, recent_tools is only association using scope of tool)

3)ToolTranslation (child of tool)

I want to solve my n+1, and write the includes for this. Right now im stucked:

ContentType.includes(recent_tools: :tool_translation)

This should work I guess accorting to guides, but this includes always returns me a full list of tools, instead of recent_tools, and all of the translations for them.

This is my tool.rb

class Tool < ApplicationRecord
  has_one :tool_translation, -> { where(locale: I18n.locale) }, dependent: :destroy

  belongs_to :content_type

  scope :recent, ->(number){ limit(number) }
end

And content_type model:

class ContentType < ApplicationRecord
  has_many :tools, dependent: :destroy
  has_many :recent_tools, -> { recent(3) }, class_name: "Tool"
end

Where I am missing? Can someone explain? Maybe its a bad logic to get a recent tools(it needed because I need only 3 last tools of content_type on main page)? How should I write the includes correctly? Thanks!

1

There are 1 best solutions below

1
Atul Yadav On

Hope this will work

ContentType.includes(:recent_tools, recent_tools: :tool_translation)

In case not, please let me know.