acts_as_taggable_on: how to optimize the query?

£可爱£侵袭症+ 提交于 2019-12-09 05:37:15

问题


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.


回答1:


Try

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




回答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?




回答3:


Use this:

Post.includes(:tags).all

and then:

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



来源:https://stackoverflow.com/questions/7777069/acts-as-taggable-on-how-to-optimize-the-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!