Q:

How to cache top N posts ordered by rating?

I'm writing a Rails 5 JSON API.
I've got an action that returns top N blog posts based on average rating. In order to achieve low response time, I denormalized my database such that posts has a average_rating column.
I'm also caching every query like so:
# posts_controller.rb
def top
  quantity = params[:quantity]

  if quantity.to_i > 0
    render json: {
      posts: cached_top_posts(quantity)
    }, status: :ok
  else
    render json: '', status: :unprocessable_entity
  end
end

def cached_top_posts(quantity)
  Rails.cache.fetch(['top', quantity], expires_in: 1.hour) do
    Post.limit(quantity).as_json(only: [:title, :content, :average_rating])
  end
end

(Order by average_rating is in the model itself)
I am aware that this is far from optimal.
Whilst it drastically improves response time when requesting the same quantity of posts, it would be much better if, when it already cached top 1000 posts, it will not cache 100 posts, but instead would get first 100 posts out of the cached 1000.
What is a good way to achieve this?

A:

Well, after I had a good night's sleep, a simple conclusion just came into my mind.
Here it is:
# posts_controller.rb
def cached_top_posts(quantity)
  data = Rails.cache.read('top_posts')
  if data.nil? || data[:quantity] < quantity
    data = {
      :quantity => quantity,
      :posts => Post.limit(quantity).as_json(only: [:title, :content, :average_rating])
    }
    Rails.cache.write('top_posts', data, expires_in: 1.hour)
  end
  data[:posts][0...quantity]
end

