views:

83

answers:

4

Let's say that I have a widget that displays summary information about how many posts or comments that I have on a site.

What's the cleanest way to persist this information across controllers?

Including the instance variables in the application controller seems like a bad idea. Having a before filter that loads the data for each controller smells like code duplication.

Do I have to use a plugin like the Cells Plugin (http://cells.rubyforge.org/) or is there a simpler way of doing it?

Thanks in advance...

+1  A: 

Presumably, you have a single partial that displays this info. You can put the methods that fetch the data you need in ApplicationHelper or as class methods on whatever model(s) you're getting the data from. Then call that method in the partial when you need to display it.

jdl
A: 

I wound up doing something similar to this:

In controllers/application.rb

def load_sidebar
  @posts = Post.find(:all)
end

To include the sidebar in various actions I did this:

before_filter :load_sidebar, :only => [ :index ] #load from application.rb file

I made the sidebar into a shared partial.

A: 
def load_sidebar
  @posts = Post.find(:all)
end

You mentioned that you were displaying summary info. If you don't really want to load all of your posts into memory, you can do the following.

def load_sidebar
  @post_count = Post.count(:id)
end
jdl
A: 

jdl,

Thanks for following up. I should have clarified that the example was just pseudo code. I have a named scope for the data that I want to pull.