Comment

Comment by gingerlime

One comment about the caching section. Rails is generally really clever getting the cache key for you automatically.

Instead of doing

  Rails.cache.fetch("blog_#{blog.id}_posts_#{posts.max(:updated_at)}") do
    blog.posts.as_json
  end
You can (and should) actually use something like

  Rails.cache.fetch(Post.all) do
    blog.posts.as_json
  end
Or even specific scopes, e.g.

  Rails.cache.fetch(blog.posts.published) do
    blog.posts.published.as_json
  end
The cache key will include the query hash, item count in the results and the max updated_at automatically for you.

In some rare cases, you might want more control and then probably best to use something like `ActiveSupport::Cache.expand_cache_key`[0]

e.g.

  key = ActiveSupport::Cache.expand_cache_key(["blog posts", blog.posts])
  Rails.cache.fetch(key) do ... end
[0] https://api.rubyonrails.org/classes/ActiveSupport/Cache.html...
parent gingerlime 7 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton