9

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.

Sunny
  • 5,825
  • 2
  • 31
  • 41
ErwinM
  • 5,051
  • 2
  • 23
  • 35

3 Answers3

13

Try

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

madomausu
  • 321
  • 2
  • 3
  • 4
    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`. – ErwinM Oct 17 '11 at 08:39
  • 3
    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. – Jan Drewniak Jan 03 '14 at 11:13
  • 1
    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).all` – tirdadc May 20 '14 at 14:35
3

Use this:

Post.includes(:tags).all

and then:

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

Varun
  • 870
  • 2
  • 10
  • 27
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?

  • Do you have created the appropriate indexes? – panmari Jul 15 '15 at 11:10
  • What you mean? Where I can find the appropriate indexes to create? –  Jul 15 '15 at 11:38
  • Usually the ones created by default https://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. – panmari Jul 16 '15 at 11:58