Optimizing queries with acts_as_taggable_on

2019-07-14 12:46发布

问题:

Using Rails 3.1 and gem 'acts-as-taggable-on' version 2.1.1.

I have a class:

class Meal < ActiveRecord::Base
  acts_as_taggable_on :foods
  ...
end

I have several different scopes on Meal that I use on a dashboard-type page. In the controller, I call, for example:

def index
  @today = Meal.from_today
  @yesterday = Meal.from_yesterday
end

I iterate over @today and @yesterday separately on the dashboard page.

I'd like to optimize the database calls. Right now, I call <%= meal.food_list %> in the view while iterating over each meal in both @today and @yesterday. For each meal, it queries the database to find the foods.

I've been trying to chain the queries in the controller with something like:

@today = Meal.from_today.includes(:foods)

but that doesn't work. Given this situation, how should I optimize the queries? Am I misusing acts-as-taggable-on?