Rails 3 Relation object
Normally in a Rails application, you want to cache three things: rendered template snippets, controller logic and model results. Rails has solutions for each one, but it was difficult to balance each tier. Often times, people will cache templates but still let their controller logic run.
With the new Active Record functionality and Relation objects, it makes simple to get a lot of speed out of just changing a little application logic. The trick is that queries are not run until you call it from the view with the .all .each methods on the Relation object, so if you would like to push the cache logic to the view layer, simply use a model query without these methods and use as like this:
In the controller:
def index @posts = Post.where(:published => true).limit(20) end
In the view:
<% @posts.each do |post| %> <%= post.title %> <% end %>
In this case, the query will be executed when we call .each. If we wrap that in a cache block, it will be executed only the cache is invalidated.
- sandor's blog
- Login to post comments
Welcome at my blog section! You can find my interests here. Maybe in my mother-language or in english, the choice is mine, but I hope you will spend nice amusement here.
This blog is about:
- Programming
- Motorcycling
- Paragliding
- Gardening
sandor's tweets
- How many tricks of these you already know? Me only few. http://t.co/kcRTEjgd — 3 days 7 hours ago
- Fight for Scottish Independence, but not for the republic! http://t.co/EXuWxhU5 — 3 days 7 hours ago
- Just switched to NetworkManager on Archlinux. I circumambulating it, but connecting to a VPN network is only two clicks. — 3 days 11 hours ago
- jQuery scoll effects. http://t.co/a5Ym9GPD — 4 days 6 hours ago
- jQuery file upload demo. http://t.co/sOl4F79u — 4 days 7 hours ago
- Just posted a photo http://t.co/75z4uOvq — 4 days 12 hours ago
- Sublime Text 2 tips. I really like this editor btw. http://t.co/aN88Duy8 — 5 days 5 hours ago
- http://t.co/SKTbSTTw Great idea — 5 days 6 hours ago
- 1 of 82
- ››
