---
title: "Rails 5.2 added method write_multi to cache store"
description: "Rails 5.2 added method write_multi to cache store"
canonical_url: "https://www.bigbinary.com/blog/rails-5.2-adds-write_multi-for-cache-writes"
markdown_url: "https://www.bigbinary.com/blog/rails-5.2-adds-write_multi-for-cache-writes.md"
---

# Rails 5.2 added method write_multi to cache store

Rails 5.2 added method write_multi to cache store

- Author: Rohan Pujari
- Published: July 3, 2018
- Categories: Rails 5.2, Rails

Before 5.2 it was not possible to write multiple entries to cache store in one
shot even though cache stores like Redis has
[`MSET`](https://redis.io/commands/mset) command to set multiple keys in a
single atomic operation. However we were not able to use this feature of Redis
because of the way Rails had implemented caching.

Rails has implemented caching using an abstract class
`ActiveSupport::Cache::Store` which defines the interface that all cache store
classes should implement. Rails also provides few common functionality that all
cache store classes will need.

Prior to Rails 5.2 `ActiveSupport::Cache::Store` didn't have any method to set
multiple entities at once.

In Rails 5.2, [write_multi was added](https://github.com/rails/rails/pull/29366)
. Each cache store can implement this method and provide the functionality to
add multiple entries at once. If cache store does not implement this method,
then the default implementation is to loop over each key value pair and sets it
individually using `write_entity` method.

Multiple entities can be set as shown here.

```ruby
Rails.cache.write_multi name: 'Alan Turning', country: 'England'
```

[redis-rails](https://github.com/redis-store/redis-rails) gem provides redis as
cache store. However it does not implement `write_multi` method.

However if we are using Rails 5.2, then there is no point in using `redis-rails`
gem, as Rails 5.2 comes with built in support for redis cache store, which
implements `write_multi` method. It was added by
[this PR](https://github.com/rails/rails/pull/31134).

We need to make following change.

```ruby
# before
config.cache_store = :redis_store

# after
config.cache_store = :redis_cache_store
```

`redis-rails` repo has a
[pull request](https://github.com/redis-store/redis-rails/pull/81) to notify
users that development of this gem is ceased. So it's better to use redis cache
store that comes with Rails 5.2.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5.2-adds-write_multi-for-cache-writes)
