mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
[ci skip] Add "Low-Level Caching" part to "Caching With Rails"
This commit is contained in:
parent
409fbffc92
commit
d361d9303b
1 changed files with 20 additions and 0 deletions
|
@ -140,6 +140,26 @@ You can also combine the two schemes which is called "Russian Doll Caching":
|
|||
|
||||
It's called "Russian Doll Caching" because it nests multiple fragments. The advantage is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.
|
||||
|
||||
### Low-Level Caching
|
||||
|
||||
Sometimes you need to cache a particular value or query result, instead of caching view fragments. Rails caching mechanism works great for storing __any__ kind of information.
|
||||
|
||||
The most efficient way to implement low-level caching is using the `Rails.cache.fetch` method. This method does both reading and writing to the cache. When passed only a single argument, the key is fetched and value from the cache is returned. If a block is passed, the result of the block will be cached to the given key and the result is returned.
|
||||
|
||||
Consider the following example. An application has a `Product` model with an instance method that looks up the product’s price on a competing website. The data returned by this method would be perfect for low-level caching:
|
||||
|
||||
```ruby
|
||||
class Product < ActiveRecord::Base
|
||||
def competing_price
|
||||
Rails.cache.fetch("#{cache_key}/competing_price", expires_in: 12.hours) do
|
||||
Competitor::API.find_price(id)
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
NOTE: Notice that in this example we used `cache_key` method, so the resulting cache-key will be something like `products/233-20140225082222765838000/competing_price`. `cache_key` generates a string based on the model’s `id` and `updated_at` attributes. This is a common convention and has the benefit of invalidating the cache whenever the product is updated. In general, when you use low-level caching for instance level information, you need to generate a cache key.
|
||||
|
||||
### SQL Caching
|
||||
|
||||
Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
|
||||
|
|
Loading…
Reference in a new issue