Sig
Sig

Reputation: 5948

Rails - Caching all the users with a specific attribute value

In a Rails 6 app, I have a page that shows all the users who are admins. Since the list changes very seldom I'd like to cache the fragment.

How can I handle such a cache?

I suppose to invalidate it I should have some kind of after_save callback in the user model to check if the saved user just became an admin or he's not anymore.

Any ideas?

Upvotes: 0

Views: 135

Answers (1)

nuaky
nuaky

Reputation: 2086

No need for callbacks. You can set cache key, so every time there is new admin, key will change and new cache will be generated. For example:

<% cache "admin-list-#{@admins.count}" do %>
  <% @admins.each do |admin| %>
    <%= admin.name %>
  <% end %>
<% end %>

In case when admin details will change and number of admin users will be the same, you can use collection caching:

https://guides.rubyonrails.org/caching_with_rails.html#collection-caching

<%= render partial: 'users/admin', collection: @admins, cached: true %>

To test caching in development use this command: rails dev:cache

Upvotes: 2

Related Questions