# Caching in Rails

**URL:** <https://www.ruby-forum.com/t/caching-in-rails/163082>\
**Category:** Rails\
**Created:** [March 17, 2009, 7:57am UTC](https://www.ruby-forum.com/t/caching-in-rails/163082 "2009-03-17T07:57:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Don\_F](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f04885/32.png) [@Don\_F](https://www.ruby-forum.com/u/Don_F)\
**Post date:** [March 17, 2009, 7:57am UTC](https://www.ruby-forum.com/t/caching-in-rails/163082/1 "2009-03-17T07:57:20Z")

</div>

I have a page that requires a lot of DB access to create a section of  
it, but that section does not change very often. I know how to cache  
the fragment in the view, but the db is still accessed in the  
controller. I watched the railscasts on fragment caching and he does  
it by moving the logic to the model. Is that the only way to do it?  
The part of the page that changes on every display is the advertising  
so I can not cache the entire page.

---

<div class="post-metadata">

**Author:** ![Don\_F](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f04885/32.png) [@Don\_F](https://www.ruby-forum.com/u/Don_F)\
**Post date:** [March 17, 2009, 8:07am UTC](https://www.ruby-forum.com/t/caching-in-rails/163082/2 "2009-03-17T08:07:19Z")

</div>

On 17 Mar., 07:56, Don F. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I have a page that requires a lot of DB access to create a section of  
> it, but that section does not change very often. I know how to cache  
> the fragment in the view, but the db is still accessed in the  
> controller. I watched the railscasts on fragment caching and he does  
> it by moving the logic to the model. Is that the only way to do it?  
> The part of the page that changes on every display is the advertising  
> so I can not cache the entire page.

You can use the #fragment\_exists? method in your controller action.  
This allows you to avoid querying the database if it’s not neseccary.

def action  
unless fragment\_exists? “fragment”  
# Execute SQL here…  
end  
end

–  
Cheers,  
David K.  
[http://twitter.com/rubyguy](http://twitter.com/rubyguy)
