简体   繁体   English

如何正确使用包括解决N + 1条轨道

[英]How to correctly use includes to solve N+1 rails

I have 3 models: 我有3种型号:

1)ContentType (parent) 1)ContentType(父级)

2)RecentTools (last 3 childs of ContentType, model is Tool, recent_tools is only association using scope of tool) 2)RecentTools(ContentType的最后三个子代,模型是Tool,最近使用的工具是使用工具范围的关联)

3)ToolTranslation (child of tool) 3)ToolTranslation(工具的子代)

I want to solve my n+1, and write the includes for this. 我想解决我的n + 1,并为此编写包含文件。 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 这是我的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: 和content_type模型:

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)? 获取最新工具可能是不好的逻辑(需要这样做是因为我只需要在主页上使用最后3个content_type工具)? How should I write the includes correctly? 我应该如何正确编写包含? Thanks! 谢谢!

Hope this will work 希望这会起作用

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

In case not, please let me know. 如果没有,请通知我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM