acts_as_taggable_on: how to optimize the query?
Asked Answered
A

3

10

I use acts_as_taggable_on in my current Rails project. On one overview page i am displaying an index of objects with their associated tags. I use the following code:

class Project < ActiveRecord::Base
  acts_as_taggable_on :categories
end

class ProjectsController < ApplicationController
  def index
    @projects = Project.all
  end
end

# in the view
<% @projects.each do |p| %>
   <%= p.name %>
   <% p.category_list.each do |t| %>
     <%= t %>
   <% end %>
<% end %>

This all works as expected. However, if i am displaying 20 projects, acts_as_taggable_on is firing 20 queries to fetch the associated tags.

How can I include the loading of the tags in the original db query?

Thanks for you time.

Abeokuta answered 15/10, 2011 at 9:48 Comment(0)
E
14

Try

@projects = Project.includes(:categories).all

Erode answered 15/10, 2011 at 12:3 Comment(3)
that's it thanks. I tried this, but it didn't work because i was using category_list to display the tags. It works if you just use Project.categories.Abeokuta
just ran into this myself, I used '.includes' and instead of using 'category_list' I used something like categories.map{|cat| cat.name} in the view, and still saw a huge performance boost.Hannelorehanner
If you are using multiple acts_as_taggable_on attributes on the same model, you also need to include all of them for this work. EX: Project.includes(:categories, :topics).allAutoharp
F
3

Use this:

Post.includes(:tags).all

and then:

post.tags.collect { |t| t.name }

Falcone answered 22/7, 2016 at 6:24 Comment(1)
This is the one that improved the performance with rails serializers!Kalagher
H
2

I agree with Jan Drewniak, huge performance boosted with

Download.includes(:tags).all

and in views:

download.tags.map {|t| link_to t, t.name}.join(', ')

But still too slow.

Any other idea?

Haymo answered 22/4, 2015 at 10:58 Comment(3)
Do you have created the appropriate indexes?Leandro
What you mean? Where I can find the appropriate indexes to create?Haymo
Usually the ones created by default github.com/mbleigh/acts-as-taggable-on/tree/master/db/migrate are enough. Do these exist in your project? You might want to check using ActiveRecords explain, i. e execute download.tags.explain and see if an index is used.Leandro

© 2022 - 2024 — McMap. All rights reserved.