0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RubyonRails:acts-as-taggable-onのN+1問題を解決する

Last updated at Posted at 2020-12-21

環境

Rails.version
=> "5.2.4.1"
ActsAsTaggableOn::VERSION
=> "6.5.0"
model
class Model < ApplicationRecord
  acts_as_taggable
end

解決策

N+1を解消するためにはincludes(:tags)を使った上で、tag_listではなく、tagsを呼ぶこと

# tagsを呼ぶこと
Model.includes(:tags).each{|m| m.tags }

# acts_as_taggable skills などとした場合
Model.includes(:tags).each{|m| m.skills }

# tag_listを呼んでしまうとN+1がどうしても発生してしまう
# Model.includes(:tags).each{|m| m.tag_list }

# tag_listと同じにするには ...
Model.includes(:tags).each{|m| m.tags.map(&:name) }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?