mercredi 27 avril 2016

Caching sql queries in a Rails controller

I have this code:

class RecipeToolsController < Api::BaseController
      skip_before_filter :set_cache_buster

      def index
        expires_in 30.minutes, public: true

        recipe = Recipe.find(params[:recipe_id])
        recipe_tools = (recipe.recipe_tools + RecipeTool.generic)

        render json: recipe_tools, each_serializer: Api::V20150315::RecipeToolSerializer
        ...
  end

The RecipeTool.generic code queries the same 3 RecipeTool objects every time. Is there a way to cache that query so it doesn't have to fire every single time?

.generic is simply this scope:

scope :generic, -> { where(generic: true) }

What can I do to cache this and expire it every so often?

This is an API endpoint.

It just seems silly that this always queries a very similar subject of RecipeTools unless the tools change. So who should be expiring this cache? Can the user of the API request a cache refresh?

Aucun commentaire:

Enregistrer un commentaire