Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

acts_as_taggable_on: how to optimize the query?

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.

like image 831
ErwinM Avatar asked Oct 15 '11 09:10

ErwinM


2 Answers

Use this:

Post.includes(:tags).all

and then:

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

like image 128
Varun Avatar answered Oct 09 '22 06:10

Varun


Try

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

like image 38
madomausu Avatar answered Oct 09 '22 04:10

madomausu