index category = Category.all render status: 200, json: category, each_serializer: CategorySerializer end end # Cache を利⽤した場合 def index render status: 200, json: cached_categories end def cached_categories Rails.cache.fetch("categories", expires_in: 24.hours) do category = Category.all render_to_string json: category, each_serializer: CategorySerializer end end
Processing by V1::CategoriesController#index as HTML Category Load (12.3ms) SELECT DISTINCT `categories`.* FROM `categories` ... ↳ app/controllers/v1/categories_controller.rb:10:in `block in cached_categories' [active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Json (9.24ms) Completed 200 OK in 125ms (Views: 1.0ms | ActiveRecord: 32.0ms | Allocations: 48349) Started GET "/v1/categories" for ::1 at 2020-10-16 15:06:52 +0900 Processing by V1::CategoriesController#index as HTML Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 226) ActiveRecordの読み込みとActiveModelSerializersによるレンダリングがキャッシュによって 省略されました。