MVC Frameworks – Where to Load Data for Sidebars

frameworksmvcruby-on-rails

This seems extremely basic, but I've read a lot of related questions and haven't found a proper answer.

Using Ruby on Rails or other similar MVC framework, how am I supposed to load data that is displayed in sidebars on multiple pages?

Options I know of, with the problems I see:

  • Load it in every controller method that needs it: causes duplication of code;
  • Load it in a method on the ApplicationController, which is executed by all controllers: would cause data to be loaded even when not needed;
  • Load it directly from the model in the view: not MVC?

I've asked this elsewhere and some people told me to "look into [insert another pattern here]" or "use Ajax calls to get the data". Although those might also work, I'm looking for an answer regarding MVC frameworks on the server.

Best Answer

Typically, I think the duplication is best handled by pushing the shared code up into a superclass (either in ApplicationController or some other superclass your controller inherits from) as a private method. I think nowadays DHH wants you to put your shared code in modules (erm, i mean concerns), and include those in your controllers, as opposed to shoving everything in ApplicationController.

Depending on your situation you'd either run the code in a before_filter on each controller action where you have your sidebar, or put the before_filter up in a superclass and call skip_before_filter when you dont want the code run before a specific controller action.

Also, its certainly possible to use ajax to accomplish this but unless you have a really good reason, I would avoid doing it that way.

There are also times when I think calling class methods on a model directly from a view is perfectly OK. Like getting simple counts, for example.

Related Topic